Has_dualstack_ipv6() Function Of Python Socket Module


  • If creating a TCP/UDP socket which can support both IPv4 and IPv6 based client connections is possible, then the method has_dualstack_ipv6() returns True
  • It returns False if the platform supports only IPv4.

Example - UDP Server:

# Example Python program that uses 
# the Python function socket.has_dualstack_ipv6() 
# to determine whether both AF_INET4 and AF_INET6
# are supported for an UDP server
import socket

dualStacked = socket.has_dualstack_ipv6()
print("The platform supports sockets in IPv4 & IPv6:%s"%dualStacked)

inet6Address = "2402:e280:215d:21b:f473:ead9:e6d7:3afd"
inet4Address = ""
port         = 1235

# Create an UDP socket with AF_INET4 or AF_INET6
# based on capability
if dualStacked:
    udpSock = socket.socket(socket.AF_INET6, 
    udpSock.bind((inet6Address, port))
    udpSock = socket.socket(socket.AF_INET4, 
    udpSock.bind((inet4Address, port))

# Print messages received from UDP clients
   print("Listening for Datagrams:")    
   pack = udpSock.recvfrom(1024)
   clientMessage = pack[0]
   clientAddress = pack[1]
   print("Client at %s has sent %s:"%(clientAddress, clientMessage))


Server Output:

The platform supports sockets in IPv4 & IPv6:True

Listening for Datagrams:

Client at ('2402:e280:215d:21b:f473:ead9:e6d7:3afd', 59797, 0, 0) has sent:ping


Listening for Datagrams:

Client & Client output:

echo ping | nc -u 2402:e280:215d:21b:f473:ead9:e6d7:3afd 1235

pinging back...


Copyright 2022 © pythontic.com