0

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,

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Gribouillis
1

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)
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.