Learning Python Network Programming

(Sean Pound) #1

Network Programming and Python


Yes, this means that the first piece of Python that we're going to write is going
to generate an exception. But, it will be a good exception. We'll learn from it.
So, fire up your Python shell and run the following command:





import smtplib








smtplib.SMTP('127.0.0.1', port=66000)





What are we doing here? We are importing smtplib, which is Python's standard
library for working with the SMTP protocol. SMTP is an application layer protocol,
which is used for sending e-mails. We will then try to open an SMTP connection by
instantiating an SMTP object. We want the connection to fail and that is why we've
specified the port number 66000, which is an invalid port. We will specify the local
host for the connection, as this will cause it to fail quickly, rather than make it wait
for a network timeout.


On running the preceding command, you should get the following traceback:


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/smtplib.py", line 242, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python3.4/smtplib.py", line 321, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python3.4/smtplib.py", line 292, in _get_socket
self.source_address)
File "/usr/lib/python3.4/socket.py", line 509, in
create_connection
raise err
File "/usr/lib/python3.4/socket.py", line 500, in
create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

This was generated by using Python 3.4.1 on a Debian 7 machine. The final error
message will be slightly different from this if you run this on Windows, but the stack
trace will remain the same.


Inspecting it will reveal how the Python network modules act as a stack. We can
see that the call stack starts in smtplib.py, and then as we go down, it moves into
socket.py. The socket module is Python's standard interface for the transport
layer, and it provides the functions for interacting with TCP and UDP as well as for
looking up hostnames through DNS. We'll learn much more about this in Chapter 7,
Programming with Sockets, and Chapter 8, Client and Server Applications.

Free download pdf