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 protocols directly.

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 wrapper (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 portable 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.

Beyond basic data communication tasks, this module also includes a ...

Get Programming Python, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.