Python中的getaddrinfo失败
我的Python脚本使用getaddrinfo()来解析一个地址,然后才能进行'bind()'操作。
这是脚本的一部分:
def fetch_ipv6_address(addr="::1"):
# try to detect whether IPv6 is supported at the present system and
# fetch the IPv6 address of localhost.
if not socket.has_ipv6:
raise Exception("the local machine has no IPv6 support enabled")
addrs = socket.getaddrinfo(addr, 0, socket.AF_INET6, socket.SOCK_RAW, 0x73, socket.AI_PASSIVE)
....
....
sockaddr = fetch_ipv6_address("::1")
RX = socket.socket(socket.AF_INET6, socket.SOCK_RAW, 0x73)
RX.bind(sockaddr)
当我运行这个脚本时,它会报错:
# ./ip6_l2tp_ip.py
Traceback (most recent call last):
File "./ip6_l2tp_ip.py", line 36, in <module>
sockaddr = fetch_ipv6_address("::1")
File "./ip6_l2tp_ip.py", line 26, in fetch_ipv6_address
addrs = socket.getaddrinfo(addr, 0, socket.AF_INET6, socket.SOCK_RAW, 0x73, socket.AI_PASSIVE)
socket.gaierror: [Errno -8] Servname not supported for ai_socktype
你知道getaddrinfo()的参数哪里出问题了吗?
谢谢!
1 个回答
1
这里提到的 0
作为第二个参数,如果它是一个长整型或整型,会被转换成字符串,这样就能符合底层API调用对 ai_servname
字段的要求。
另一方面,文档中写到
o For internet address families, if you specify servname while you set
ai_socktype to SOCK_RAW, getaddrinfo() will raise an error, because
service names are not defined for the internet SOCK_RAW space.
如果你把那个 0
替换成 None
,就可以正常工作了。