Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python lookup hostname from IP with 1 second timeout

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!

like image 974
ensnare Avatar asked Apr 04 '10 20:04

ensnare


People also ask

How do I find the hostname in Python?

Get Hostname in Python platform. node() function returns a string that displays the information about the node basically the system's network name.

How do I find the server name from an IP address?

Click the Windows Start button, then "All Programs" and "Accessories." Right-click on "Command Prompt" and choose "Run as Administrator." Type "nslookup %ipaddress%" in the black box that appears on the screen, substituting %ipaddress% with the IP address for which you want to find the hostname.


2 Answers

>>> 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.

like image 187
ChristopheD Avatar answered Sep 27 '22 20:09

ChristopheD


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.

like image 24
adamse Avatar answered Sep 27 '22 19:09

adamse