【发布时间】:2026-01-20 21:55:02
【问题描述】:
我想知道是否有办法使用 python 来解析仅在 ipv6 中解析的主机名和/或在 ipv4 和 ipv6 中都解析的主机名?
socket.gethostbyname() 和 socket.gethostbyname_ex() 不适用于 ipv6 解析。
执行此操作的一种虚拟方法是运行实际的 linux 主机命令并解析结果。有没有更好的方法来做到这一点?
谢谢,
【问题讨论】:
我想知道是否有办法使用 python 来解析仅在 ipv6 中解析的主机名和/或在 ipv4 和 ipv6 中都解析的主机名?
socket.gethostbyname() 和 socket.gethostbyname_ex() 不适用于 ipv6 解析。
执行此操作的一种虚拟方法是运行实际的 linux 主机命令并解析结果。有没有更好的方法来做到这一点?
谢谢,
【问题讨论】:
socket.getaddrinfo 支持 IPv6。您只需将family 设置为AF_INET6。
socket.getaddrinfo("example.com", None, socket.AF_INET6)
【讨论】:
[Errno 11004] getaddrinfo failed,但是当使用nslookup -query=AAAA google.com时它返回一些IPv6地址。有没有办法通过使用 python 脚本获得相同的 IPv6 地址?
我想更详细地扩展@john-colanduoni 的答案。
要真正仅获得相应的 IPv6 地址,您应该尝试使用socket.getaddrinfo。
>>> print(socket.getaddrinfo('www.microsoft.com', None, socket.AF_INET6)[0][4][0])
2a02:26f0:6a:288::356e
但要小心,例如如果主机名没有 IPv6 AAAA-Record,例如:
>>> 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
你会得到socket.gaierror: [Errno -2] Name or service not known,它是OSError的子类。
顺便说一句。尝试使用localhost、您计算机的hostname(如果它启用了IPv6)或example.com 作为主机名参数。
对 PTR-Record 的查询如下所示:
>>> print(socket.gethostbyaddr('2a00:1450:4001:81d::200e')[0])
fra15s18-in-x0e.1e100.net
因为socket.gethostbyaddr 同时启用了 IPv4 和 IPv6。
【讨论】:
[Errno 11004] getaddrinfo failed
import socket? *.com/questions/7334199/…
google.com 上尝试过