Question

This is an additional question in regards to this post: Python raw_input with forced TLD?

I have a check in place to see if a string ends with a TLD,

TLD = ('.com', '.info', '.org', '.net')
if raw_input("Please enter a hostname").endswith(TLD):
# blah blah

But I am attempting to store the raw_input in to a variable. Would the proper coding practice be to do something such as:

TLD = ('.com', '.info', '.org', '.net')
hostName = raw_input(":").lower()
<<piece of code that determines if hostName does in fact end with a TLD?>>

If so, what would that look like? I attempted a while True: and an if elif statement but I am not getting anywhere, I have googled endlessly with no results which is why I post this question here.

The program in question will grab the hostname, say google.com, determine if it has a valid TLD, strip the TLD off of hostName and store it in hostNameshort (both will be used later), if it doesn't get a proper TLD prompt again with emphasis on that it needs the TLD during input time, and then continue on once it does.

Was it helpful?

Solution

Something like this:

TLD = ('.com', '.info', '.org', '.net')
hostName = raw_input(":").lower()
while not hostName.endswith(TLD):
    print "Incorrect input, Try again!"
    hostName = raw_input(":").lower()

Demo:

:foo.bar
Incorrect input, Try again!
:google.in
Incorrect input, Try again!
:yahoo.com

OTHER TIPS

Actual DNS lookup to test a TLD

Ohh, while we are at it, maybe a short snippet to actually test TLD's against the DNS servers might become handy. I'm using the dnspython module from the Nominum guys:

import dns.resolver

def testTLD(tld):
    try:
        dns.resolver.query(tld + '.', 'SOA')
        return True
    except dns.resolver.NXDOMAIN:
        return False

for tld in ('com', 'org', 'klonk', 'dk'):
    print "TLD \"{tld}\" exists: {bool}".format(tld=tld, bool=testTLD(tld))

and it runs like this:

TLD "com" exists: True
TLD "org" exists: True
TLD "klonk" exists: False
TLD "dk" exists: True
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top