Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind IPv6 address to Python socket as source ip address

I formerly used the code below to bind IPv4 address to Python socket as source ip address.

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

Does above code work for IPv6 address? If not, how can I bind an IPv6 address?

Thanks in advance!

like image 722
jack Avatar asked Jun 13 '12 02:06

jack


1 Answers

you can try this, to get an IPV6 address, it is recommend that you use socket.getaddrinfo it will return all the different address both IPV4 and IPV6, you can bind them all or just which ever one you want/need.

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
like image 102
Samy Vilar Avatar answered Oct 11 '22 14:10

Samy Vilar