11

If I have an IP address like 2001:4860:4860::8888

How can I get the fully qualified domain in the format foo.ip6.arpa ?

EDIT: Both the solutions so far give me google-public-dns-a.google.com - maybe Reverse DNS was the wrong name. For this I'd expect the output to be something like 8.8.8.8.0...etc.ip6.arpa

Ivy
  • 3,393
  • 11
  • 33
  • 46
  • Answers look correct to me despite the edited question. But is there no standard module capable of returning the `.ip6.arpa` format? – Pavel Šimerda Jan 22 '15 at 20:13

2 Answers2

16

IPy provides methods for what you want:

>>> from IPy import IP
>>> ip = IP('127.0.0.1')
>>> ip.reverseName()
'1.0.0.127.in-addr.arpa.'

Works for both IPv4 and IPv6, although the original IPy has a few bugs for IPv6. I created a fork with some extensions and fixes at https://github.com/steffann/python-ipy which you can use as long as the fixes haven't been merged back into the original code.

Update:

You can of course also use the getnameinfo function in built-in socket module:

>>> import socket
>>> socket.getnameinfo(('2001:4860:4860::8888', 0), 0)
('google-public-dns-a.google.com', '0')
>>> socket.getnameinfo(('127.0.0.1', 0), 0)
('localhost', '0')

You need to provide a host+port tuple, but you can provide 0 for the port, and you'll get the hostname back.

Eric Wong
  • 1,388
  • 7
  • 17
Sander Steffann
  • 9,509
  • 35
  • 40
  • It should be noted, that `socket.getnameinfo` is not really reverse DNS resolution (which would mean to ask only/exactly the DNS). With `socket.getnameinfo` other sources like `/etc/hosts` may be taken into account as well (and typically are even before asking the DNS). And DNS may not even be asked at all. – calestyo Jan 16 '23 at 05:15
11

using dnspython.

from dns import resolver,reversename
addr=reversename.from_address("2001:4860:4860::8888")
str(resolver.query(addr,"PTR")[0])
Vinayak Kolagi
  • 1,831
  • 1
  • 13
  • 26