python-3.xdnsgethostbyaddr

python3: socket.gethostbyaddr(): "Unknown host" vs "Host name lookup failure"


I am using socket.gethostbyaddr() in python3 to resolve IP to hostname.

I need to distinguish between 3 cases:

1) success (IP resolved to hostname)
2) IP address has no DNS record
3) DNS server is temporarily unavailable

I am using simple function:

def host_lookup(addr):
    try:
        return socket.gethostbyaddr(addr)[0]
    except socket.herror:
        return None

and then I want to call this function from my main code:

res = host_lookup('45.82.153.76')

if "case 1":
    print('success')
else if "case 2":
    print('IP address has no DNS record')
else if "case 3":
    DNS server is temporarily unavailable
else:
    print('unknown error')

When I try socket.gethostbyaddr() in python console, I get different error codes in each case:

>>> socket.gethostbyaddr('45.82.153.76')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.herror: [Errno 1] Unknown host

and when I deliberatrely make DNS unreachable:

>>> socket.gethostbyaddr('45.82.153.76')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.herror: [Errno 2] Host name lookup failure

So how can I differentiate between these cases in my code above ?


Solution

  • socket.herror is a subclass of OSError that provides access to the numeric error code errno:

    import socket
    
    def host_lookup(addr):
        return socket.gethostbyaddr(addr)[0]
    
    try:
        res = host_lookup("45.82.153.76")
        print('Success: {}'.format(res))
    except socket.herror as e:
        if e.errno == 1:
            print('IP address has no DNS record')
        elif e.errno == 2:
            print('DNS server is temporarily unavailable')
        else:
            print('Unknown error')