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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With