O'Reilly logo

Programming Python, Second Edition by Mark Lutz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

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. The socket module also includes tools for converting bytes to a standard network ordering, wrapping socket objects in simple file objects, and more. It supports socket programming on any machine that supports BSD-style sockets -- MS Windows, Linux, Unix, etc. -- and so provides a portable socket interface.

Socket Basics

To create a connection between machines, Python programs import the socket module, create a socket object, and call the object’s methods to establish connections and send and receive data. Socket object methods map directly to socket calls in the C library. For example, the script in Example 10-1 implements a program that simply listens for a connection on a socket, and echoes back ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required