[英]Python resolve a host name with IPv6 address
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?我想知道是否有办法使用 python 来解析仅在 ipv6 中解析的主机名和/或在 ipv4 和 ipv6 中解析的主机名?
socket.gethostbyname()
and socket.gethostbyname_ex()
does not work for ipv6 resolution. socket.gethostbyname()
和socket.gethostbyname_ex()
不适用于 ipv6 解析。
A dummy way to do that is to run actual linux host command and parse the results.一种虚拟的方法是运行实际的 linux 主机命令并解析结果。 Is there any better way to do that?
有没有更好的方法来做到这一点?
Thanks,谢谢,
socket.getaddrinfo supports IPv6. socket.getaddrinfo支持 IPv6。 You just need to set
family
to AF_INET6
.您只需要将
family
设置为AF_INET6
。
socket.getaddrinfo("example.com", None, socket.AF_INET6)
I want to expand on the answer of @john-colanduoni with more detail.我想更详细地扩展@john-colanduoni 的答案。
To really get only the corresponding IPv6-address, you should try using socket.getaddrinfo .要真正得到的只是相应的IPv6地址,你应该尝试使用socket.getaddrinfo 。
>>> print(socket.getaddrinfo('www.microsoft.com', None, socket.AF_INET6)[0][4][0])
2a02:26f0:6a:288::356e
but beware, eg if there is no IPv6 AAAA-Record for the hostname, such as:但要注意,例如,如果主机名没有 IPv6 AAAA 记录,例如:
>>> 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 ofOSError .你会得到
socket.gaierror: [Errno -2] Name or service not known
这是OSError的子类。
Btw.顺便提一句。 try using
localhost
, the hostname
of your computer (if it's IPv6 enabled) or example.com
as the hostname argument.尝试使用
localhost
、您计算机的hostname
(如果它启用了 IPv6)或example.com
作为主机名参数。
A query for the PTR-Record would look like:对 PTR-Record 的查询如下所示:
>>> print(socket.gethostbyaddr('2a00:1450:4001:81d::200e')[0])
fra15s18-in-x0e.1e100.net
since socket.gethostbyaddr is both IPv4 and IPv6 enabled.因为socket.gethostbyaddr启用了 IPv4 和 IPv6。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.