Python lookup hostname from IP with 1 second timeout
Asked Answered
H

2

66

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!

Hyksos answered 4/4, 2010 at 20:20 Comment(0)
G
110
>>> 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.

Gentian answered 4/4, 2010 at 20:28 Comment(8)
what about something like 'http:/1.0.1.0/blah/blahm.html' ?Paratuberculosis
@Eiyrioü von Kauyf: That was not the question asked (return a hostname when specified an ip address).Gentian
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.Paratuberculosis
@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 precisiousCustody
Does not work for mapped ipv4: ----> 1 socket.gethostbyaddr('::ffff:69.59.196.211') error: Address family not supported by protocolRepellent
socket has its own method to set a timeout: docs.python.org/2/library/socket.html#socket.socket.settimeoutOphidian
('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'])Effects
Does this handle ipv6 addresses or only ipv4?Annettaannette
D
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.

Decima answered 4/4, 2010 at 20:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.