http://www.ietf.org
http://www.iana.org/numbers.html
http://www.iana.org/assignments/port-numbers
http://www.w3.org
It’s not impossible that more recent repositories for standard protocol specifications
will arise during this book’s shelf life, but the IETF website will likely be the main
authority for some time to come. If you do look, though, be warned that the details are,
well, detailed. Because Python’s protocol modules hide most of the socket and mes-
saging complexity documented in the protocol standards, you usually don’t need to
memorize these documents to get web work done with Python.
Socket Programming
Now that we’ve seen how sockets figure into the Internet picture, let’s move on to
explore the tools that Python provides for programming sockets with Python scripts.
This section shows you how to use the Python socket interface to perform low-level
network communications. In later chapters, we will instead use one of the higher-level
protocol modules that hide underlying sockets. Python’s socket interfaces can be used
directly, though, to implement custom network dialogs and to access standard proto-
cols manually.
As previewed in Chapter 5, the basic socket interface in Python is the standard library’s
socket module. Like the os POSIX module, Python’s socket module is just a thin wrap-
per (interface layer) over the underlying C library’s socket calls. Like Python files, it’s
also object-based—methods of a socket object implemented by this module call out to
the corresponding C library’s operations after data conversions. For instance, the C
library’s send and recv function calls become methods of socket objects in Python.
Python’s socket module supports socket programming on any machine that supports
BSD-style sockets—Windows, Macs, Linux, Unix, and so on—and so provides a port-
able socket interface. In addition, this module supports all commonly used socket
types—TCP/IP, UDP, datagram, and Unix domain—and can be used as both a network
interface API and a general IPC mechanism between processes running on the same
machine.
From a functional perspective, sockets are a programmer’s device for transferring bytes
between programs, possibly running on different computers. Although sockets them-
selves transfer only byte strings, we can also transfer Python objects through them by
using Python’s pickle module. Because this module converts Python objects such as
lists, dictionaries, and class instances to and from byte strings, it provides the extra step
needed to ship higher-level objects through sockets when required.
Socket Programming | 787