I want to write a python script to convert IP addresses to hostnames. I am using a Linux box. I don't see this information in whois command. Are there any commands that always give the correct hostnames (as accurately as possible)?
Asked
Active
Viewed 1.5k times
3
-
2I think you are confused about the concepts involved. – Apr 07 '11 at 06:11
-
edit- sorry I meant hostname !! – Illusionist Apr 07 '11 at 06:31
-
1Apart from a python solution, you can also use the `host` command, for both forwards and reverse DNS lookups. – tzot Apr 30 '11 at 18:41
2 Answers
14
Socket library has an API to do reverse DNS lookups.
import socket
socket.gethostbyaddr("8.8.8.8")
>>> ('google-public-dns-a.google.com', [], ['8.8.8.8'])
Keep in mind that not all IP addresses will have reverse DNS entries, not all aliases might be present in the answer to this query etc.

Tadeusz A. Kadłubowski
- 8,047
- 1
- 30
- 37
-
Is it the reason why am I not getting the domain name when IP being passed as in above – Tara Prasad Gurung Aug 31 '17 at 04:40
3
The closest you're likely to get is socket.getfqdn(). It incorporates the results from gethostbyaddr(). Pass it an IP address as a string.

ʇsәɹoɈ
- 22,757
- 7
- 55
- 61