且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Python中反向DNS查找

更新时间:2022-04-21 08:19:21

IPy 提供您想要的方法:

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

适用于IPv4和IPv6,尽管原始IPy对于IPv6有一些错误.我在 https://github.com/steffann/python-ipy ,只要未将这些修订合并到原始代码中就可以使用.

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.

您当然也可以使用内置的 socket 模块:

You can of course also use the 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')

您需要提供一个host + port元组,但是您可以为该端口提供 0 ,然后您将获得主机名.

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