Introduction

Network and communication programming are particularly powerful uses of any programming language. It is much more common these days for computers to interface with one another (or with an entire network, such as the Internet) than it is for a machine to act alone, and knowing exactly how that communication takes place is an important skill for any programmer. If you happen to be a Python aficionado, you may be aware that Python has several complete libraries designed to make network programming simple.
.

Prerequisites

  • Any version of Python (See our Guide for installing Python 2.7 in Centos)
  • Basic understanding of Python

Sockets

One of the most basic–and useful–import libraries is the socket library. It allows the programmer to define, create, use, and destroy network connections known as sockets.

So what exactly is a socket? In network terms, a socket is the endpoint of a connection, defined by an IP address and a port number. A connection uses a pair of sockets: source and destination.

Programs normally use sockets to allow two computers to communicate. Sockets can also be used to pass data between different applications or even different parts of the same program. We can demonstrate how a socket works with either two applications or two separate parts of a running application: a server portion, which listens for connections, and a client portion, which attempts to connect to a server. When your computer requests a web page, for instance, it opens a socket, usually binding it to port 80 (for HTTP), and connects to a web server, using the same port and socket identifier. All related communication goes through that endpoint. When communication finishes, the client closes the socket and the connection to which it is bound.

The socket library in Python is well-developed and easy to use. To use the library put import socket at the beginning of your program. This command gives your program access to all of the socket library’s included functions, such as socket() (create a new socket object), socketpair() (create a pair of new socket objects), and gethostbyname() (map a hostname to its IP address), to name a few.
.

Experimenting with the Socket Library

To experiment with sockets on our local machine, we’ll write a Python script to create a server application that creates an open socket. Then we’ll run that code and, in another terminal window, telnet to our local machine (on localhost) using the port we opened in the server script.

Let’s start with a script we’ll call server.py. This program will open a socket, bind it to a port and protocol, and then listen for connections.

import socket # (1)  
host = '' # (2)  
port = 1234 # (3)  

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # (4)  
s.bind((host, port)) # (5)  

print 'Socket created' # (6)  
s.listen(10) # (7)  
print 'Socket listening' # (8)  

conn, addr = s.accept() # (9)  

print 'Connected with ' + addr[0] + ':' + str(addr[1]) # (10)  

Save this file as server.py. In a terminal window (or at the command prompt, if you’re using Windows), navigate to the location of your file and run it.

python server.py

Leave it running and open a second terminal window. In that window, initiate a telnet connection to the localhost on port 1234.

telnet localhost 1234

Once it connects, you should see the original terminal window print out ‘Connected with 127.0.0.1:60426’ or something similar, while your client window will briefly show ‘Connected to localhost’ before the connection terminates.
.

What the Socket Code Is Doing

So what’s going on here? Let’s look at each line:

Line (1) imports the socket library and makes it available for use. Lines (2) and (3) set variables for host and port, respectively. The blank host variable (that’s an empty string surrounded by single quotes, incidentally, NOT a double quotation mark) means that the server application will be listening on all available interfaces, including localhost, which is the one we’ll use to connect.

Line (4) creates the socket itself, using two parameters. The first parameter, AF_INET, means that we’re using IPv4 addresses (as opposed to IPv6 addresses). The second parameter, SOCK_STREAM, means that this socket will use TCP packets (UDP traffic uses the type SOCK_DGRAM and works a little bit differently–but that’s beyond the scope of this article). Line (5) binds the socket we’ve created to the (host, port) tuple.

Line (7) tells the program to listen for connections to the socket we bound in line (5). The 10 parameter indicates that the server will accept up to 10 connections before refusing a client.

Line (9) assigns variables to the connection once the server accepts a connection. Line (10) prints the IP address and port number of the client that has made the connection with the server.
.

Keeping the Socket Open

When we tested this code, we saw that the server closed the connection immediately, which is not particularly helpful. So that we can see data transferred back and forth over the connection, we’ll add four lines of code to our server.py program.

data = conn.recv(1024) # 11  
conn.sendall(data) # 12  
conn.close() # 13  
s.close() # 14  

Again, if you run this code in a terminal window, and then connect (from another terminal) with telnet localhost 1234, you’ll connect to localhost, but this time the connection will remain open. Type a word into the telnet window and then press Return; the word will be echoed back to that same screen, and then the connection will close.

In line (11), the data variable stores the data received over the connection.

Line (12) sends that data back over the connection back to the client–echoing it, in other words.

Finally, lines (13) and (14) practice a little housekeeping by closing the connection and destroying the socket–never a bad idea, especially when coding a socket-based application that will be released into the wild.
.

Conclusion

This script is a very basic example of how to create a network connection using Python’s socket module, communicate across the connection, and then close it again. While a full-grown application will be much more complicated, the basic communication structure–and the theory behind it–remains the same.

We hope that you have enjoyed this tutorial and have learned enough to get you started with working with sockets in Python. Be sure to check back again for more tutorials, and to check out our reliable VPS hosting solutions.
.
.