Bob G Bob G - 1 month ago 7
Python Question

How to return "Host is not resolvable" message after gethostbyname failiure

This might be a something simple here, but I'm still learning python.
Basically I'm trying to pull an IP address from a hostname, which works fine, but if the host does not resolve it errors. I have it now so that once it resolves the IP address it populates it to a text box, so what i'm trying to do here is if it fails to resolve... To put a message in that text box saying no host found or whatever. I get an error: "socket.gaierror: [Errno 11004] getaddrinfo failed" when it does not resolve.

This is the code i have:

def findip():
host = hname.get() # Pulls host from text box1
ip = gethostbyname(host)
ipaddress.set(ip) #exports to text box2
return


So what i don't know is the If command needed for the failure (if that makes any sense) it would be something like:

if "gethostbyname fails"
ipaddress.set("Host does not resolve")
else
ipaddress.set(ip)


Any thought would be appreciated. Thanks in advance :)

Answer

You have to try and catch the exception, this way:

def findip():
    host = hname.get()
    try:
        ip = gethostbyname(host)
    except socket.gaierror:
        ip = "Host does not resolve"

    ipaddress.set(ip)

Just make sure you have the socket module imported or it won't work, if you have no need for the socket module you can import the the exception only, so you need to do either of these:

import socket
import socket.gaierror