PYTHON · PYTHON FOR EVERYONE · CHAPTER 14

Sockets

Build your own TCP server and client, send syslog events over UDP and serve several clients at once.

8 min readCourse: Python for EveryoneLevel: beginner

From point A to point B

Point A: you know TCP, UDP and ports from the OSI model, and your programs already read and write files. But they don't talk to another program over the network yet. Point B: by the end of this chapter, you'll create a TCP server and client with the socket module, send UDP messages the way syslog does and serve several clients at once with socketserver.

What a socket is

A socket is one end of a communication between two programs. Those programs can be on the same machine or on two different continents. When your browser opens a website or a router sends a message to a syslog server, there's a socket at each end.

A network socket is identified by 3 pieces of data: the IP address, the port and the transport protocol. In Python, everything you need is in the socket module, and when you create one, you choose 2 things:

  • The family: socket.AF_INET for IPv4 (the one you'll use here), socket.AF_INET6 for IPv6 and socket.AF_UNIX to connect processes on the same machine through a special file.
  • The type: socket.SOCK_STREAM for TCP, connection-oriented and reliable, or socket.SOCK_DGRAM for UDP, which sends standalone datagrams with no delivery guarantee.

If you call socket.socket() with no arguments, you get an AF_INET socket of type SOCK_STREAM. In the examples, we write them out explicitly so you can see what you're choosing.

Bytes travel over the network

A network doesn't carry letters; it carries bytes. That's why, in Python 3, send() and recv() work with bytes objects, not with str. Before sending text, you encode it with .encode(); when you receive it, you decode it with .decode(). Both sides must use the same encoding, usually UTF-8.

text = "Site: São Paulo"
data = text.encode("utf-8")
print(data)                          # → b'Site: S\xc3\xa3o Paulo'
print(len(text), len(data))          # → 15 16
print(data.decode("utf-8"))          # → Site: São Paulo
print(type(b"quit"), b"quit" == "quit")   # → <class 'bytes'> False

The ã takes up 2 bytes in UTF-8, so the text has 15 characters but 16 bytes. And look at the last line: b"quit" and "quit" aren't equal. Comparing what you receive with a regular string is a common mistake.

Python 3.14 update. The book sent strings directly, as in send("hello"), because in Python 2 str was a sequence of bytes. In Python 3, str is Unicode text and send("hello") raises TypeError. Use "hello".encode("utf-8") or the literal b"hello".

A TCP server step by step

A TCP server always follows the same sequence:

  1. Create the socket with socket.socket().
  2. Bind it to an address and a port with bind(). It takes a (host, port) tuple.
  3. Listen with listen(). The optional argument says how many pending connections, not yet accepted, the system can queue.
  4. Accept a connection with accept(). It blocks the program until a client arrives and returns a new socket to talk to it, plus its address.
  5. Exchange data with recv() and sendall() on that new socket.
  6. Close both sockets with close().
import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("127.0.0.1", 9999))
server.listen(1)
print("Waiting for a connection on port 9999...")

client, (ip, port) = server.accept()
print(f"Connection from {ip}:{port}")
data = client.recv(1024)
print("Received:", data)
client.sendall(data)

client.close()
server.close()

3 details deserve an explanation:

  • recv(1024) returns at most 1024 bytes. If the other end closed the connection, it returns b"".
  • sendall() keeps going until all the data is sent. send() also exists, but it may send only part of it and returns how many bytes went out; you'd have to resend the rest yourself.
  • The setsockopt line turns on SO_REUSEADDR. Without it, if you restart the server right away, you may see OSError: [Errno 98] Address already in use: the system keeps the port reserved for a while after the connection closes.

About the address: "127.0.0.1" only accepts connections from the machine itself, the safest choice for practicing. With "" or "0.0.0.0", you'd listen on every IPv4 interface, and any device on the network could connect.

A TCP client

The client is shorter. It creates the socket, connects with connect(), which takes the same (host, port) tuple as bind(), and uses sendall() and recv().

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 9999))
s.sendall("show version".encode("utf-8"))
response = s.recv(1024)
print("Response:", response.decode("utf-8"))
s.close()

Open 2 terminals. In the first one, run basic_server.py; in the second, basic_client.py:

$ python3 basic_server.py
Waiting for a connection on port 9999...
Connection from 127.0.0.1:39236
Received: b'show version'
$ python3 basic_client.py
Response: show version

The operating system picks the client's port (39236 in this case), and it changes on every run. If you run the client without the server up, you get ConnectionRefusedError: [Errno 111] Connection refused: nobody is listening on that port.

Full example: echo server and client

Now an example with a conversation. The client sends whatever you type and the server returns it as is, like an echo. Everything ends when you type quit.

This version uses with. Just like with files, the block closes the socket when you leave it, even if an error occurs.

import socket

HOST, PORT = "127.0.0.1", 9999

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((HOST, PORT))
    server.listen(1)
    print(f"Echo server on {HOST}:{PORT}")
    connection, address = server.accept()
    with connection:
        print("Client connected:", address)
        while True:
            data = connection.recv(1024)
            if not data or data == b"quit":
                break
            print("Received:", data.decode("utf-8"))
            connection.sendall(data)
print("Bye")
import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect(("127.0.0.1", 9999))
    while True:
        message = input("> ")
        s.sendall(message.encode("utf-8"))
        if message == "quit":
            break
        response = s.recv(1024)
        print("Echo:", response.decode("utf-8"))
print("Bye")

Save them as echo_server.py and echo_client.py. Here's what a session looks like in each terminal:

$ python3 echo_server.py
Echo server on 127.0.0.1:9999
Client connected: ('127.0.0.1', 39240)
Received: hello
Received: show ip interface brief
Bye
$ python3 echo_client.py
> hello
Echo: hello
> show ip interface brief
Echo: show ip interface brief
> quit
Bye

The server leaves the loop in 2 cases: when it receives b"quit" and when recv() returns b"", a sign that the client closed the connection. Checking the second case avoids an infinite loop if the client is interrupted with Ctrl+C.

Fact. TCP is a byte stream, not a sequence of messages. A single recv() can bring half a message or 2 messages together. It works here because the client waits for each response before sending the next one. Real protocols mark where each message ends with a delimiter, such as a newline, or with a prefix that gives the length.

Modern shortcuts: create_server and create_connection

Python 3.8 added 2 functions that wrap up the previous steps. socket.create_server() creates the socket, turns on SO_REUSEADDR on POSIX systems like Linux and macOS, and calls bind() and listen(). socket.create_connection() creates the socket and connects; it also accepts a timeout in seconds.

import socket

with socket.create_server(("127.0.0.1", 9999)) as server:
    connection, address = server.accept()
    with connection:
        data = connection.recv(1024)
        connection.sendall(data.upper())
import socket

with socket.create_connection(("127.0.0.1", 9999), timeout=5) as s:
    s.sendall(b"hostname r1")
    print(s.recv(1024))      # → b'HOSTNAME R1'

The timeout matters on real networks. Without it, a client can wait forever for a device that doesn't respond. If it runs out, Python raises TimeoutError. You can also set it on any socket with settimeout().

UDP: a mini syslog receiver

With UDP, there's no connection: listen(), accept() and connect() aren't required. Each datagram travels on its own and carries its destination. That's why you use 2 other methods: sendto(data, (host, port)) to send and recvfrom(bufsize) to receive, which returns the data and the source address.

Syslog is a good example: routers send their events over UDP, traditionally to port 514. On Linux, ports below 1024 require privileges, so the example uses 5514.

import socket

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
    s.bind(("127.0.0.1", 5514))
    print("Listening for syslog on UDP 5514...")
    for _ in range(2):
        data, (ip, port) = s.recvfrom(4096)
        print(f"{ip} -> {data.decode('utf-8', errors='replace')}")
import socket

events = [
    "<187>Oct 24 10:01:12 R1 %LINK-3-UPDOWN: Interface Gi0/1, changed state to down",
    "<189>Oct 24 10:04:00 R1 %SYS-5-CONFIG_I: Configured from console",
]
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
    for event in events:
        sent = s.sendto(event.encode("utf-8"), ("127.0.0.1", 5514))
        print(f"Sent {sent} bytes")
$ python3 syslog_receiver.py
Listening for syslog on UDP 5514...
127.0.0.1 -> <187>Oct 24 10:01:12 R1 %LINK-3-UPDOWN: Interface Gi0/1, changed state to down
127.0.0.1 -> <189>Oct 24 10:04:00 R1 %SYS-5-CONFIG_I: Configured from console
$ python3 send_syslog.py
Sent 78 bytes
Sent 64 bytes

The number between < and > is the syslog priority: facility × 8 + severity. 187 is facility local7 (23 × 8 = 184) with severity 3. errors="replace" keeps an invalid byte from stopping the receiver. If you run the sender without a receiver, there's no error: UDP doesn't confirm delivery.

Python 3.14 update. The book only covered TCP and named the UDP methods as recvfrom and "sendfrom". The second one doesn't exist: the correct method is sendto(). Also, the book closed sockets by hand with close(); since Python 3.2, sockets support with, which is the recommended way.

Several clients with socketserver

The echo server serves a single client and exits. A real server must serve many, often at the same time. The standard library's socketserver module handles that structure: you only write what to do with each client.

You define a class that inherits from BaseRequestHandler and write its handle() method. Inside it, self.request is the client's socket and self.client_address, its address. ThreadingTCPServer serves each client in a separate thread; you'll see threads in a later chapter.

import socketserver


class EchoHandler(socketserver.BaseRequestHandler):
    def handle(self):
        print("Client connected:", self.client_address)
        while True:
            data = self.request.recv(1024)
            if not data or data == b"quit":
                break
            self.request.sendall(data)
        print("Client disconnected:", self.client_address)


class EchoServer(socketserver.ThreadingTCPServer):
    allow_reuse_address = True


with EchoServer(("127.0.0.1", 9999), EchoHandler) as server:
    print("Echo server with socketserver on port 9999")
    server.serve_forever()

serve_forever() serves clients until you stop the program with Ctrl+C. The allow_reuse_address = True attribute is equivalent to the earlier SO_REUSEADDR. Since the protocol is the same, echo_client.py works unchanged. With 2 clients connected at once, the server shows something like this:

$ python3 socketserver_server.py
Echo server with socketserver on port 9999
Client connected: ('127.0.0.1', 54472)
Client connected: ('127.0.0.1', 54482)
Client disconnected: ('127.0.0.1', 54482)
Client disconnected: ('127.0.0.1', 54472)

The second client connected while the first was still active and finished first. With the earlier echo server, it would have had to wait. For many thousands of connections, Python also offers asyncio, a different model that's worth studying later.

Challenge

Answer before you open the solution.

1. Your client runs s.sendall("show run") and fails with TypeError. Why?

Because sockets send bytes, not str. Use "show run".encode("utf-8") or b"show run".

2. What does accept() return, and why don't you use the server socket to talk to the client?

A new socket and the client's address. The original socket keeps listening to accept more connections; each client gets its own socket.

3. You restart your server and get Address already in use, even though no other process is running. What do you do?

Turn on SO_REUSEADDR before bind(). The port is still reserved by the previous connection; create_server() and allow_reuse_address = True solve it the same way.

4. What does it mean when recv() returns b""?

That the other end closed the connection. It's the signal to leave the read loop.

5. You send an event over UDP to a port where nobody is listening. What error do you get?

Usually none. sendto() hands the datagram to the network and returns; UDP doesn't confirm receipt. If you need that guarantee, use TCP.

Key takeaways

  • A socket is one end of a communication: IP, port and protocol. AF_INET + SOCK_STREAM is TCP over IPv4.
  • bytes travel through sockets: encode() when sending and decode() when receiving.
  • TCP server: bind, listen, accept, recv/sendall. Client: connect, sendall/recv.
  • Use with, SO_REUSEADDR and timeout; create_server() and create_connection() make them simpler.
  • TCP is a stream: define where each message ends. UDP uses sendto/recvfrom and doesn't guarantee delivery.
  • socketserver lets you write only the logic for each client.

In the next chapter, you move up to HTTP: you'll query websites and REST APIs with urllib.request, without handling sockets by hand.

Official resources

Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.

Navigate