在python中使用套接字建立IPv6连接

2024-06-25 06:19:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图运行这个非常基本的套接字示例:

import socket
host = 'ipv6hostnamegoeshere'
port=9091

ourSocket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0)
ourSocket.connect((host, port))

但是,我得到了一个错误:

    ourSocket.connect((host, port))
  File "<string>", line 1, in connect
socket.error: [Errno 22] Invalid argument

布尔值has_ipv6返回true。有什么帮助吗?


Tags: importhost示例streamstringportconnect错误
1条回答
网友
1楼 · 发布于 2024-06-25 06:19:44

正如socket.connect docs所说,AF_INET6需要一个4元组:

sockaddr is a tuple describing a socket address, whose format depends on the returned family (a (address, port) 2-tuple for AF_INET, a (address, port, flow info, scope id) 4-tuple for AF_INET6), and is meant to be passed to the socket.connect() method.

例如:

>>> socket.getaddrinfo("www.python.org", 80, 0, 0, socket.SOL_TCP)
[(2, 1, 6, '', ('82.94.164.162', 80)),
 (10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))]

>>> ourSocket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0)
>>> ourSocket.connect(('2001:888:2000:d::a2', 80, 0, 0))

相关问题 更多 >