I need to write a small bit of code that will print an error if I cannot resolve the name to IP.
I see that you can use the "socket.gethostbyaddr" methods but I cant seem to find a simple method/exception for when it does not find an IP address.

Also if I change the timeout on this would it affect the dns timeout`s for the whole machine ?

Or is there a simpler method ?

Thanks,

You can look at this and see if it helps.

>>> import socket 
>>> socket.gethostbyname_ex('python.org')
('python.org', [], ['82.94.164.162'])
>>> socket.gethostbyaddr('82.94.164.162')
('dinsdale.python.org', [], ['82.94.164.162'])
>>> socket.gethostbyaddr('111.111')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
gaierror: [Errno 11004] getaddrinfo failed
>>> socket.gethostbyaddr('11.111.111.111')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
herror: [Errno 11004] host not found
import socket

def foo(ip):
    try:
        name = socket.gethostbyaddr(ip)
        return name[0]
    except (socket.gaierror,socket.herror):
        return 'No DNS name found for this ip'

#ip = '82.94.164.162'
#dinsdale.python.org

ip = '11.111.111.111'
#No DNS name found for this ip

print foo(ip)

I think except socket.error will catch all errors from module socket.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.