Python resolve a host name with IPv6 address

元气小坏坏 提交于 2019-12-23 08:54:06

问题


I wonder if there is a way to use python to resolve a hostname that resolves only in ipv6 and/or for a hostname that resolves both in ipv4 and ipv6?

socket.gethostbyname() and socket.gethostbyname_ex()does not work for ipv6 resolution.

A dummy way to do that is to run actual linux host command and parse the results. Is there any better way to do that?

Thanks,


回答1:


socket.getaddrinfo supports IPv6. You just need to set family to AF_INET6.

socket.getaddrinfo("example.com", None, socket.AF_INET6)



回答2:


I want to expand on the answer of @john-colanduoni with more detail.

Get only the IPv6 address

To really get only the corresponding IPv6-address, you should try using socket.getaddrinfo.

>>> print(socket.getaddrinfo('www.microsoft.com', None, socket.AF_INET6)[0][4][0])
2a02:26f0:6a:288::356e

but beware, e.g. if there is no IPv6 AAAA-Record for the hostname, such as:

>>> print(socket.getaddrinfo('microsoft.com', None, socket.AF_INET6)[0][4][0])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.7/socket.py", line 748, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

you will get socket.gaierror: [Errno -2] Name or service not known which is a subclass of OSError.

Btw. try using localhost, the hostname of your computer (if it's IPv6 enabled) or example.com as the hostname argument.

The the hostname from IPv6 address

A query for the PTR-Record would look like:

>>> print(socket.gethostbyaddr('2a00:1450:4001:81d::200e')[0])
fra15s18-in-x0e.1e100.net

since socket.gethostbyaddr is both IPv4 and IPv6 enabled.



来源:https://stackoverflow.com/questions/15373288/python-resolve-a-host-name-with-ipv6-address

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!