Establishing an IPv6 connection using sockets in python

自作多情 提交于 2019-12-21 04:26:26

问题


I am trying to run this very basic socket example:

import socket
host = 'ipv6hostnamegoeshere'
port=9091

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

Yet, I get the error:

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

The boolean has_ipv6 returns true. Any help?


回答1:


As the socket.connect docs says, AF_INET6 expects a 4-tuple:

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.

For example:

>>> 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))


来源:https://stackoverflow.com/questions/5358021/establishing-an-ipv6-connection-using-sockets-in-python

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