I wish to create a TCP server using sockets, that binds to both IPv4 and IPv6 addresses.
Is there a way to do it without creating 2 sockets?
The feature you're looking for is called "dual-stack", or an IPv4 + IPv6 dual-stack socket.
Since Python 3.8, you're able to easily do so using socket.create_server()
.
Setting the parameter dualstack_ipv6=True
will allow you, on supported systems, to listen on both IPv4 and IPv6 addresses using the same socket.
If you wish to check if your system supports dual-stack sockets, use socket.has_dualstack_ipv6()
.
Code example from the Python docs:
import socket addr = ("", 8080) # all interfaces, port 8080 if socket.has_dualstack_ipv6(): s = socket.create_server(addr, family=socket.AF_INET6, dualstack_ipv6=True) else: s = socket.create_server(addr)