Python implements the BSD Sockets API in the socket module in its basic system library. Python adds an object-oriented interface that makes the API particularly easy to use. Otherwise, the implementation follows RFC 3493 pretty closely. The module also defines all the constants specified in RFC 3493 like AF_INET or AI_V4MAPPED. Documentation is available online as a part of the Python Library Reference [Pyth-Lib].
As in C, sockets are created using the socket() function, which returns a socket object. Following the object-oriented paradigm, all other socket functions are implemented as methods and applied to the socket object via messages. This will be demonstrated in the example below.
Python implementation also uses a simpler form of socket addresses.:
• IPv4 sockets are represented as a pair (address, port)
• IPv6 sockets are represented as a four-tuple (address, port, flowinfo, scopeid), where flowinfo and scopeid correspond to the sin6_flowinfo and sin6_scope_id members of the sockaddr_in6 structure.
Finally, the handling of error conditions was integrated into the Python system of exceptions. Instead of signalling a failure by returning an error code, as in C, Python functions raise an exception that the application can handle in a specific way.
The following example consists of two simple programs that demonstrate the Python way of using the BSD Sockets API. They should work with Python version 2.2.1 or higher. The programs realise connectionless communication using IPv6 and UDP. Both programs first execute the getaddrinfo() function to obtain the socket address and create the socket. The sender application then periodically sends a short message to a named peer using the sendto() function. The receiver binds the socket address to the socket and thus starts listening on the predefined port 54321, and then enters an infinite loop waiting for the data and printing them on the terminal.
A usual disclaimer applies here: real-life programs should also care about possible errors and define appropriate exception handlers. Also, a more graceful termination might be recommended – our programs must be abruptly terminated by pressing Ctrl-C.
