65

How can I look up a hostname given an IP address? Furthermore, how can I specify a timeout in case no such reverse DNS entry exists? Trying to keep things as fast as possible. Or is there a better way? Thank you!

ensnare
  • 40,069
  • 64
  • 158
  • 224

2 Answers2

109
>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])

For implementing the timeout on the function, this stackoverflow thread has answers on that.

Community
  • 1
  • 1
ChristopheD
  • 112,638
  • 29
  • 165
  • 179
  • what about something like 'http:/1.0.1.0/blah/blahm.html' ? – Eiyrioü von Kauyf Dec 12 '12 at 16:42
  • 8
    @Eiyrioü von Kauyf: That was not the question asked (return a hostname when specified an ip address). – ChristopheD Apr 18 '13 at 14:54
  • it's the same question - however i'm asking do you have a suggested way to normalize that and do socket.gethostbyaddr("1.0.1.0") or the like? It's the same question but the input format is different - gethostbyaddr does not like non normalized input. – Eiyrioü von Kauyf Apr 18 '13 at 17:44
  • @EiyrioüvonKauyf yes because its excactly what the method is supposed to do: ip to dns conversion... you could use a regex for that like `http(|s)://([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/.*`. there are plenty more out there, which are better or more precisious – reox Nov 18 '13 at 12:35
  • Does not work for mapped ipv4: ----> 1 socket.gethostbyaddr('::ffff:69.59.196.211') error: Address family not supported by protocol – thule Feb 21 '14 at 12:46
  • 2
    socket has its own method to set a timeout: https://docs.python.org/2/library/socket.html#socket.socket.settimeout – gdvalderrama Sep 27 '16 at 08:55
  • ('apps2.ideal-logic.com', [], ['69.59.196.211']) . this is the format of output I get when I above code. The possibility might be the ip has been changed. But I am getting such result for all my domains too like for one of my domain when passed its ip showing something like this `('ip-149-202-166.eu', [], ['149.202.166.163'])` – Tara Prasad Gurung Aug 31 '17 at 04:35
  • Does this handle ipv6 addresses or only ipv4? – ericOnline Nov 04 '20 at 00:36
22

What you're trying to accomplish is called Reverse DNS lookup.

socket.gethostbyaddr("IP") 
# => (hostname, alias-list, IP)

http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

ase
  • 13,231
  • 4
  • 34
  • 46