2011-03-18 26 views
6

我試圖運行這個非常基本的插座例如IPv6連接:建立使用套接字在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布爾。任何幫助?

回答

11

作爲socket.connect docs說,AF_INET6需要一個四元組:

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

謝謝,這解決它。 – collisionTwo 2011-03-18 23:06:50