Learning Python Network Programming

(Sean Pound) #1
Chapter 1

From the preceding program, it's clear that the smtplib module calls into the socket
module. The application layer protocol has employed a transport layer protocol
(which in this case is TCP).


Right at the bottom of the traceback, we can see the exception itself and the Errno
111. This is an error message from the operating system. You can verify this by going
through /usr/include/asm-generic/errno.h (asm/errno.h on some systems) for
the error message number 111 (on Windows the error will be a WinError, so you can
see that it has clearly been generated by the OS). From this error message we can see
that the socket module is calling down yet again and asking the operating system to
manage the TCP connection for it.


Python's network modules are working as the protocol stack designers intended
them to. They call on the lower levels in the stack to employ their services to perform
the network tasks. We can work by using simple calls made to the application layer
protocol, which in this case is SMTP, without having to worry about the underlying
network layers. This is network encapsulation in action, and we want to make as
much use of this as we can in our applications.


Taking it from the top


Before we start writing code for a new network application, we want to make sure
that we're taking as much advantage of the existing stack as possible. This means
finding a module that provides an interface to the services that we want to use,
and that is as high up the stack as we can find. If we're lucky, someone has already
written a module that provides an interface that provides the exact service we need.


Let's use an example to illustrate this process. Let's write a tool for downloading
Request for Comments (RFC) documents from IETF, and then display them on screen.


Let's keep the RFC downloader simple. We'll make it a command-line program
that just accepts an RFC number, downloads the RFC in text format, and then
prints it to stdout.


Now, it's possible that somebody has already written a module for doing this,
so let's see if we can find anything.


The first place we look should always be the Python standard library. The modules
in the library are well maintained, and well documented. When we use a standard
library module, the users of your application won't need to install any additional
dependencies for running it.

Free download pdf