IPv6-clean programming in Python

| | Comments (0) | TrackBacks (0)

It looks like the next version of Python will include an IPv6-safe convenience function to open a connection to a server: socket.create_connection(). You can see the gory details in the svn commit message.

This is A Good Thing. It wraps a rather verbose bit of code:


msg = "getaddrinfo returns an empty list"
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
    af, socktype, proto, canonname, sa = res
    sock = None
    try:
        sock = socket(af, socktype, proto)
        if timeout is not None:
            sock.settimeout(timeout)
        sock.connect(sa)
        return sock

    except error, msg:
        if sock is not None:
            sock.close()

raise error, msg


This code requests a list of all the addresses (both IPv4 and IPv6) for host using the socket.getaddrinfo() function. It then loops over that list, trying each address until it finds one that works. If none work, it raises an exception.

Python's socket.getaddrinfo() is quite handy. It's a Python wrapper around the C getaddrinfo(3) function, which is defined in RFC 3493: Basic Socket Interface Extensions for IPv6. I'll talk more about it in a future blog entry on how to write IPv6-clean programs (and make sure they still work with IPv4).

0 TrackBacks

Listed below are links to blogs that reference this entry: IPv6-clean programming in Python.

TrackBack URL for this entry: https://blogs.psu.edu/mt4/mt-tb.cgi/642

Leave a comment