2

I am looking to make a portion of an application where the user inputs their domain and the IP addresses is resolved. If socket.gethostbyname doesn't return a result i.e. comes back with socket.gaierror: [Errno 8] nodename nor servname provided, or not known: I want to loop the input function so as the user is asked to input again until a valid result is returned for resolvedip. I have used while loops and a manner of things but can't seem to get the result I am after.

What would I need to add to the code below to achieve this ?

nsip = input("\nEnter your target website [example: google.com] : ")
resolvedip = socket.gethostbyname(nsip)#
print(resolvedip)
Thomas
  • 174,939
  • 50
  • 355
  • 478
  • 1
    Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – MisterMiyagi Feb 18 '22 at 12:15

1 Answers1

1

Do you mean something like this?

while True:
    try:
        nsip = input("\nEnter your target website [example: google.com] (q to quit) : ")
        if nsip == "q" or nsip == "quit":
            break
        resolvedip = socket.gethostbyname(nsip)
    except:
        print("Couldn't lookup: "+nsip)
        continue
    print(resolvedip)

Result:

Enter your target website [example: google.com] (q to quit) : one.one.one.one
1.0.0.1

Enter your target website [example: google.com] (q to quit) : google.com
142.250.74.142

Enter your target website [example: google.com] (q to quit) : haha.store.com
Couldn't lookup: haha.store.com

Enter your target website [example: google.com] (q to quit) : q
PS C:\Python> 
Cow
  • 2,543
  • 4
  • 13
  • 25