3

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)?

Tadeusz A. Kadłubowski
  • 8,047
  • 1
  • 30
  • 37
Illusionist
  • 5,204
  • 11
  • 46
  • 76

2 Answers2

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