The case against ipv4 sockets

Nobody needs ipv4 sockets anymore. Even in ipv4 environments. You can use mapped ipv4 addresses for receiving from and connecting to ipv4 sockets. For this you must NOT enable IPV6_V6ONLY. Remove calls like this:

socket.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 1)

This option is by default disabled so you don’t have to disable the option manually.

Python sample code for ipv6 ready sockets (client side):

import socket
from http.client import HTTPConnection
retval = socket.getaddrinfo(url, port, socket.AF_INET6, socket.SOCK_STREAM, flags=socket.AI_V4MAPPED)
if len(retval) == 1: # check if there was a result
    con = HTTPConnection(retval[0][4][:2])

Server side:

from http.server import SimpleHTTPRequestHandler, HTTPServer import socket PORT = 8000 class server(HTTPServer): address_family = socket.AF_INET6
    def verify_request(self, request, client_address):
        if client_address[0] in ["::1", "::ffff:"]: # check if localhost
            return True
        return False

httpd = server(("::", PORT), SimpleHTTPRequestHandler) # bind to anyaddress

Another pitfall is binding the server to localhost. This breaks ipv6, ipv4 compatibility as you can either specify an ipv4 mapped address or an ipv6 address. There are two solutions for this case:

  1. multiple binds (and reuseport, reuseaddr socket option)
  2. bind to anyaddress (“::”, in c:(in6addr_any)) and manually check ip addresses (easier and implemented in example, causes connection resets (port is visible))


Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s