Python’s struct module can also be used to format Python objects as packed binary
data byte strings for transmission, but is generally limited in scope to objects that map
to types in the C programming language. The pickle module supports transmission of
larger object, such as dictionaries and class instances. For other tasks, including most
standard Internet protocols, simpler formatted byte strings suffice. We’ll learn more
about pickle later in this chapter and book.
Beyond basic data communication tasks, the socket module also includes a variety of
more advanced tools. For instance, it has calls for the following and more:
- Converting bytes to a standard network ordering (ntohl, htonl)
- Querying machine name and address (gethostname, gethostbyname)
- Wrapping socket objects in a file object interface (sockobj.makefile)
- Making socket calls nonblocking (sockobj.setblocking)
- Setting socket timeouts (sockobj.settimeout)
Provided your Python was compiled with Secure Sockets Layer (SSL) support, the
ssl standard library module also supports encrypted transfers with its
ssl.wrap_socket call. This call wraps a socket object in SSL logic, which is used in turn
by other standard library modules to support the HTTPS secure website protocol
(http.client and urllib.request), secure email transfers (poplib and smtplib), and
more. We’ll meet some of these other modules later in this part of the book, but we
won’t study all of the socket module’s advanced features in this text; see the Python
library manual for usage details omitted here.
Socket Basics
Although we won’t get into advanced socket use in this chapter, basic socket transfers
are remarkably easy to code in Python. 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.
Sockets are inherently bidirectional in nature, and socket object methods map directly
to socket calls in the C library. For example, the script in Example 12-1 implements a
program that simply listens for a connection on a socket and echoes back over a socket
whatever it receives through that socket, adding Echo=> string prefixes.
Example 12-1. PP4E\Internet\Sockets\echo-server.py
"""
Server side: open a TCP/IP socket on a port, listen for a message from
a client, and send an echo reply; this is a simple one-shot listen/reply
conversation per client, but it goes into an infinite loop to listen for
more clients as long as this server script runs; the client may run on
a remote machine, or on same computer if it uses 'localhost' for server
"""
788 | Chapter 12: Network Scripting