2012-06-13 156 views
6

我以前使用下面的代碼IPv4地址綁定到Python插座作爲源IP地址。綁定IPv6地址到Python插座作爲源IP地址

import socket 
true_socket = socket.socket 
def bound_socket(*a, **k): 
    sock = true_socket(*a, **k) 
    sock.bind((sourceIP, 0)) 
    return sock 
socket.socket = bound_socket 

上面是否對IPv6的地址編碼工作?如果沒有,我如何綁定IPv6地址?

在此先感謝!

回答

6

你可以試試這個,讓一​​個IPV6地址,它是建議您使用socket.getaddrinfo將返回所有不同的地址,IPv4和IPv6時,可以將它們全部或只是你想要哪一方/需要。

import socket 
def bound_socket(*a, **k): 
    sock = socket.socket(*a, **k) 
    if socket.AF_INET6 in a: 
     if not socket.has_ipv6: 
      raise ValueError("There's no support for IPV6!") 
     else: 
      address = [addr for addr in socket.getaddrinfo(source_ip, None) 
         if socket.AF_INET6 == addr[0]] # You ussually want the first one. 
      if not address: 
       raise ValueError("Couldn't find ipv6 address for source %s" % source_ip) 
      sock.bind(address[0][-1]) 
    else: 
     sock.bind((source_ip, 0)) 
    return sock 
2

這應該做的伎倆...設置地址家庭。

import socket 
s = socket.socket(family=socket.AF_INET6) 
s.bind(('::1', 1234)) 
3

如果你真的想要一個廣泛的解決方案,可以擴展您的解決方案使用getaddrinfo()

import socket 
l = socket.getaddrinfo(None, "", 0, socket.SOCK_STREAM, 0, socket.AI_PASSIVE) 
for i in l: print i 

這給

(2, 1, 6, '', ('0.0.0.0', 0)) 
(10, 1, 6, '', ('::', 0, 0, 0)) 

這些都是你應該創建一個套接字參數:

s = socket.socket(i[0], i[1], i[2]) 
if i[0] == AF_INET6: s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) 
s.bind(i[4]) 

現在您擁有的協議數量儘可能多,您可以使用它們。

如果你有一個給定主機名/ IP綁定到(唉,IPV6_V6ONLY下不老的Windows版本......工作),做

l = socket.getaddrinfo("mylocalIP", None, 0, socket.SOCK_STREAM, 0, socket.AI_PASSIVE) 

,它會選擇正確的地址/協議族的你:

>>> socket.getaddrinfo("::1", None, 0, socket.SOCK_STREAM, 0, socket.AI_PASSIVE) 
[(10, 1, 6, '', ('::1', 0, 0, 0))] 
>>> socket.getaddrinfo("127.0.0.1", None, 0, socket.SOCK_STREAM, 0, socket.AI_PASSIVE) 
[(2, 1, 6, '', ('127.0.0.1', 0))] 
>>> socket.getaddrinfo("localhost", None, 0, socket.SOCK_STREAM, 0, socket.AI_PASSIVE) 
[(10, 1, 6, '', ('::1', 0, 0, 0)), (2, 1, 6, '', ('127.0.0.1', 0))] 
>>> socket.getaddrinfo("192.168.1.32", None, 0, socket.SOCK_STREAM, 0, socket.AI_PASSIVE) 
[(2, 1, 6, '', ('192.168.1.32', 0))] 

2 VS 10AF_INETAF_INET6; socket.AI_PASSIVE表示您需要bind() ing的地址。