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
  • 7,642
  • 1
  • 28
  • 36
Illusionist
  • 4,754
  • 8
  • 41
  • 69

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
  • 7,642
  • 1
  • 28
  • 36
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Ɉ
  • 21,294
  • 7
  • 52
  • 59