ZetCode

Python Socket

last modified November 19, 2026 Python 3.15

This tutorial introduces network programming with Python's standard-library socket module. We resolve host names, exchange data with local TCP and UDP servers, frame messages on a TCP stream, send simple HTTP requests, and finish with an asyncio echo server. All examples use only the standard library.

A socket is a communication endpoint. A server waits for requests at an address, and a client sends requests to that address. The programs can run on different computers or on the same computer. Not all sockets establish a connection: UDP sockets exchange independent messages.

The module exposes the operating system's Berkeley sockets API. It works with bytes rather than Python strings: use encode('utf-8') to send text and decode('utf-8') after receiving a complete text message.

Note: These small servers bind to 127.0.0.1, the IPv4 loopback address, so only programs on the same computer can reach them. Binding to 0.0.0.0 would listen on all local IPv4 interfaces and could expose the server to other computers. These examples are not production servers.

Network protocols

TCP/IP is the family of protocols used on the Internet and many local networks. TCP provides a reliable, ordered byte stream while a connection is working; network failures can still interrupt it. UDP sends individual messages, called datagrams, without guaranteeing delivery, order, or freedom from duplicates.

With the IPv4 or IPv6 address family, socket.SOCK_STREAM selects TCP by default and socket.SOCK_DGRAM selects UDP. TCP does not preserve message boundaries: one call to sendall need not correspond to one call to recv. UDP preserves datagram boundaries, although an undersized receive buffer can truncate a datagram or cause an error, depending on the platform.

Address families

An address family determines the kind of address a socket accepts. Common families are:

For AF_INET, an address is a (host, port) tuple. The host is a name such as localhost or an IPv4 address such as 127.0.0.1. The integer port identifies a service on that host. IPv6 socket addresses use (host, port, flowinfo, scope_id) tuples; the IPv6 loopback address is ::1.

Python get IP address

The smallest example resolves localhost to an IPv4 address and creates a TCP socket without connecting it. A with statement closes the socket automatically, including when an exception occurs.

get_ip.py
import socket

host = 'localhost'
address = socket.gethostbyname(host)
print(f'{host}: {address}')

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    print(f'Type: {sock.type.name}')

The socket constructor takes an address family and a socket type. The type attribute is a SocketKind enum member, so its name gives a readable label. The gethostbyname function returns only an IPv4 address; the next section shows a resolver that also handles IPv6. Results depend on the host configuration; the output below is from a machine where localhost resolves to 127.0.0.1.

$ python get_ip.py
localhost: 127.0.0.1
Type: SOCK_STREAM

Resolving addresses with getaddrinfo

The getaddrinfo function is the general resolver. It returns a list of candidate addresses, each with the family, socket type, and protocol needed to create a matching socket. It handles IPv4 and IPv6 alike.

addr_info.py
import socket

for host in ['localhost', '::1']:
    results = socket.getaddrinfo(host, 8001, type=socket.SOCK_STREAM)

    for family, kind, proto, canonname, sockaddr in results:
        print(f'{host:10} {family.name:9} {kind.name:12} {proto} {sockaddr}')

Each result is a five-item tuple: family, socket type, protocol number, canonical name, and socket address. The canonical name is empty unless the AI_CANONNAME flag is passed. Without the type argument, the function would list each address again for UDP and raw sockets. Protocol 6 is TCP.

Note the different socket-address shapes: a two-item tuple for IPv4 and a four-item tuple for IPv6. A host name can resolve to several addresses; on many systems localhost also yields ::1. A client should try the results in order until one connects, which is what create_connection does for us.

$ python addr_info.py
localhost  AF_INET   SOCK_STREAM  6 ('127.0.0.1', 8001)
::1        AF_INET6  SOCK_STREAM  6 ('::1', 8001, 0, 0)

Python TCP echo server

An echo server sends received bytes back unchanged. Start this server in one terminal, then run the client from the next section in another. The server handles one connection and then exits; restart it for each client run.

echo_server.py
import socket

address = ('127.0.0.1', 8001)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
    server.bind(address)
    server.listen()
    print('Listening on 127.0.0.1:8001', flush=True)

    connection, peer = server.accept()
    with connection:
        connection.settimeout(5)
        while True:
            data = connection.recv(1024)
            if not data:
                break
            connection.sendall(data)

The bind method assigns the local address. The listen method marks the socket as a listening socket, and accept waits for a client. It returns a new connected socket and the client's address. Data is exchanged on that new socket, not the listening socket. The operating system chooses a default queue size for pending connections when listen has no argument.

The loop echoes every block until recv returns b'', meaning the peer has closed its sending direction and no unread bytes remain. The sendall method keeps sending until all supplied bytes have been passed to the socket or an error occurs. Unlike send, it does not require us to handle a partial send. It does not confirm that the peer's application has processed the data.

The listening socket intentionally waits indefinitely for a client. The connected socket has a five-second timeout, so an idle client cannot leave this example waiting forever. An unhandled timeout ends the program with a traceback. If the port is already occupied, stop the other server or change the port in both programs. Press Ctrl+C to stop a server that is still waiting.

$ python echo_server.py
Listening on 127.0.0.1:8001

Python TCP echo client

The client connects to the echo server, sends a short UTF-8 message, and reads the reply in a loop. A receive buffer size is a maximum, not a request to wait for exactly that many bytes.

echo_client.py
import socket

address = ('127.0.0.1', 8001)
message = 'Hello from TCP!'.encode('utf-8')
reply = bytearray()

with socket.create_connection(address, timeout=5) as sock:
    sock.sendall(message)
    sock.shutdown(socket.SHUT_WR)

    while True:
        data = sock.recv(1024)
        if not data:
            break
        reply.extend(data)

print(reply.decode('utf-8'))

The create_connection helper creates and connects a TCP socket. When given a host name, it resolves the name with getaddrinfo and tries the addresses in turn until one succeeds. Here we use an explicit IPv4 address to match the server. The five-second timeout also applies to subsequent socket operations.

The call to shutdown(socket.SHUT_WR) closes only the sending direction. This is a half-close: the client can still read the echo, but the server knows that no more request bytes will arrive. After echoing all data, the server leaves its loop and closes its connection, which ends the client's receive loop. Without an agreed end-of-message rule, both programs could wait for each other.

We collect the bytes before decoding because a UTF-8 character can be split between two reads. Reading until end-of-stream works for this one-request connection, but a connection that carries several messages needs another boundary; the next section adds one.

$ python echo_client.py
Hello from TCP!

Message framing

Since TCP is a byte stream, a protocol must define where one message ends and the next begins. Common choices are a delimiter such as a newline, or a length prefix. We put the length-prefix helpers into a module so that both the server and the client can import them.

framing.py
import socket

HEADER_SIZE = 4
MAX_SIZE = 64 * 1024


def recv_exactly(sock: socket.socket, size: int) -> bytes:
    data = bytearray()
    while len(data) < size:
        chunk = sock.recv(size - len(data))
        if not chunk:
            raise ConnectionError('Connection closed mid-message')
        data.extend(chunk)
    return bytes(data)


def send_message(sock: socket.socket, payload: bytes) -> None:
    header = len(payload).to_bytes(HEADER_SIZE, 'big')
    sock.sendall(header + payload)


def recv_message(sock: socket.socket) -> bytes | None:
    first = sock.recv(1)
    if not first:
        return None
    header = first + recv_exactly(sock, HEADER_SIZE - 1)
    size = int.from_bytes(header, 'big')
    if size > MAX_SIZE:
        raise ValueError(f'Message too large: {size} bytes')
    return recv_exactly(sock, size)

Every message starts with a four-byte header holding the payload length as a big-endian unsigned integer; int.to_bytes and int.from_bytes convert between the two forms. Header and payload go out in a single sendall call.

The recv_exactly function repeats recv until the requested number of bytes has arrived, since a single call may return fewer. The recv_message function first reads one byte on its own: an end-of-stream at that point is a clean close between messages, reported as None, while an end-of-stream later is an error. The MAX_SIZE check rejects a corrupt or hostile length before any memory is used for the payload.

Framed TCP server

The server now handles a sequence of messages on one connection. It replies to each message with the upper-cased text, using the same framing.

framed_server.py
import socket

from framing import recv_message, send_message

address = ('127.0.0.1', 8003)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
    server.bind(address)
    server.listen()
    print('Listening on 127.0.0.1:8003', flush=True)

    connection, peer = server.accept()
    with connection:
        connection.settimeout(5)
        while (message := recv_message(connection)) is not None:
            text = message.decode('utf-8')
            print(f'Received: {text}', flush=True)
            send_message(connection, text.upper().encode('utf-8'))

The assignment expression := receives a message and tests it in one step. The loop ends when the client closes the connection after a complete message. A peer that disappears mid-message raises ConnectionError, and an idle peer triggers the five-second timeout. The output shows the server terminal after the client from the next section has run.

$ python framed_server.py
Listening on 127.0.0.1:8003
Received: falcon
Received: sky
Received: čerešňa

Framed TCP client

The client sends three words over a single connection and reads one reply after each request. No half-close is needed because the length prefix tells the server where each message ends.

framed_client.py
import socket

from framing import recv_message, send_message

address = ('127.0.0.1', 8003)
words = ['falcon', 'sky', 'čerešňa']

with socket.create_connection(address, timeout=5) as sock:
    for word in words:
        send_message(sock, word.encode('utf-8'))
        reply = recv_message(sock)
        if reply is None:
            raise ConnectionError('Server closed the connection')
        print(f'{word} -> {reply.decode("utf-8")}')

The length counts bytes, not characters: čerešňa has seven characters but needs ten bytes in UTF-8. Leaving the with block closes the socket, which the server sees as the clean end-of-stream between messages.

$ python framed_client.py
falcon -> FALCON
sky -> SKY
čerešňa -> ČEREŠŇA

Python UDP echo server

A UDP server receives a datagram and its sender's address, then sends a reply to that address. There is no listening or accepting step. Start this program before running the UDP client in the next section; it handles one datagram.

udp_server.py
import socket

address = ('127.0.0.1', 8002)

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server:
    server.bind(address)
    print('Waiting on 127.0.0.1:8002', flush=True)
    data, peer = server.recvfrom(1024)
    server.sendto(data, peer)

The recvfrom method returns (data, address), and sendto takes the reply bytes and the destination address. The 1024-byte buffer is sufficient for our short message. Unlike TCP's b'', an empty UDP datagram is a valid message, not an end-of-stream signal. UDP needs no framing helpers: each datagram is already one message. This server deliberately waits for a datagram until it arrives or the program is interrupted.

$ python udp_server.py
Waiting on 127.0.0.1:8002

Python UDP echo client

The UDP client sends one datagram and waits for one response. A timeout is especially important here: sending a datagram successfully does not establish that a server exists or that a reply will arrive.

udp_client.py
import socket

address = ('127.0.0.1', 8002)

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
    sock.settimeout(5)
    sock.sendto('Hello from UDP!'.encode('utf-8'), address)
    data, peer = sock.recvfrom(1024)

print(data.decode('utf-8'))

The operating system assigns a local port when the client first sends data, so an explicit bind is unnecessary here. A single recvfrom receives at most one datagram. The example trusts the local sender; a real protocol must validate replies and decide how to handle loss, duplicates, retries, and authentication. Neither raw TCP nor UDP encrypts application data.

$ python udp_client.py
Hello from UDP!

Blocking calls, timeouts, and errors

Sockets are blocking by default: operations such as accept and recv wait until they can make progress or an error occurs. A positive settimeout value limits the wait for a socket operation and raises TimeoutError on expiry. Setting the timeout to None restores blocking mode; setblocking(False), the same as a zero timeout, selects non-blocking mode. The following program triggers three common exceptions.

socket_errors.py
import socket

# Nothing listens on this port
try:
    socket.create_connection(('127.0.0.1', 8009), timeout=2)
except ConnectionRefusedError as e:
    print(f'Refused: {e}')

# A UDP socket that never receives a datagram
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
    sock.bind(('127.0.0.1', 0))
    sock.settimeout(0.5)
    try:
        sock.recvfrom(1024)
    except TimeoutError as e:
        print(f'Timed out: {e}')

    sock.setblocking(False)
    try:
        sock.recvfrom(1024)
    except BlockingIOError as e:
        print(f'Would block: {e}')

Nothing listens on port 8009, so the connection attempt fails at once with ConnectionRefusedError. The UDP socket binds to port 0, which lets the operating system pick a free port; no datagram ever arrives, so recvfrom gives up after half a second with TimeoutError. In non-blocking mode the same call fails immediately with BlockingIOError instead of waiting.

All three are subclasses of OSError, as is ConnectionResetError, raised when a peer aborts a connection. Catch them where the program can recover or report useful context. Timeouts are not an overall deadline: a receive loop can continue as long as each read succeeds in time, and host-name resolution happens outside the socket timeout. For many simultaneous connections, use selectors, asyncio, or a server framework rather than busy-waiting on non-blocking sockets. The error messages come from the operating system and differ between platforms.

$ python socket_errors.py
Refused: [Errno 111] Connection refused
Timed out: timed out
Would block: [Errno 11] Resource temporarily unavailable

A local HTTP test server

HTTP is an application protocol that can run over TCP. To make the next examples independent of public websites, create a small text file in a scratch directory and start Python's HTTP server there. These commands run in a separate terminal; stop the server with Ctrl+C when finished.

$ python -c "from pathlib import Path; Path('greeting.txt').write_bytes(b'Hello from HTTP!\n')"
$ python -m http.server 8000 --bind 127.0.0.1

The first command writes a 17-byte UTF-8 file. The server exposes files in its current directory, so use a directory without sensitive files. The Python http.server tutorial covers this development server in more detail; it is not intended for production use.

Python Socket HEAD request

The HTTP HEAD method requests response metadata without a response body. A Content-Length header, when present, describes the body that the corresponding GET response would have, not a body to read after HEAD.

head_request.py
import socket

request = (
    b'HEAD /greeting.txt HTTP/1.1\r\n'
    b'Host: 127.0.0.1:8000\r\n'
    b'Connection: close\r\n\r\n'
)
response = bytearray()

with socket.create_connection(('127.0.0.1', 8000), timeout=5) as sock:
    sock.sendall(request)
    while True:
        data = sock.recv(4096)
        if not data:
            break
        response.extend(data)

print(response.decode('iso-8859-1'), end='')

The request line contains the method, the resource path, and the HTTP version. HTTP/1.1 requires a Host header. Each line ends with \r\n, a carriage return and line feed; an empty line terminates the headers. Adjacent byte literals form a single request value.

We ask the server to close the connection so the receive loop has a clear stopping point. HTTP/1.1 otherwise uses persistent connections by default. The response headers are displayed using ISO-8859-1, which maps every byte to a character without a decoding failure. This is not a rule for decoding HTTP bodies. Python's test server responds with HTTP/1.0 by default even though the request uses HTTP/1.1. The Python version and dates in the output will vary.

$ python head_request.py
HTTP/1.0 200 OK
Server: SimpleHTTP Python/3.15.2
Date: Thu, 19 Nov 2026 13:56:48 GMT
Content-type: text/plain
Content-Length: 17
Last-Modified: Thu, 19 Nov 2026 13:56:47 GMT

Python Socket GET request

The HTTP GET method requests a representation of a resource. The following client requests the same file and separates the headers from the body at the first empty line.

get_request.py
import socket

request = (
    b'GET /greeting.txt HTTP/1.1\r\n'
    b'Host: 127.0.0.1:8000\r\n'
    b'Connection: close\r\n\r\n'
)
response = bytearray()

with socket.create_connection(('127.0.0.1', 8000), timeout=5) as sock:
    sock.sendall(request)
    while True:
        data = sock.recv(4096)
        if not data:
            break
        response.extend(data)

headers, separator, body = response.partition(b'\r\n\r\n')
if not separator:
    raise ValueError('Incomplete HTTP response headers')

print(headers.split(b'\r\n', 1)[0].decode('ascii'))
print(body.decode('utf-8'), end='')

The partition method splits only at the first header/body separator. We print the status line and decode the complete body as UTF-8 because we created this particular text file ourselves. An arbitrary HTTP body could use another character encoding or contain binary data.

This example handles the simple response from our local server, not every valid HTTP response. Other servers can use chunked transfer encoding, where the body contains length-prefixed chunks, or compression. Asking for Connection: close does not disable either feature. A full HTTP client must also handle response framing, status codes, redirects, and limits on response size. For real HTTP work, prefer urllib.request, http.client, or a higher-level HTTP library.

Plain TCP does not provide HTTPS. HTTPS uses TLS to encrypt traffic and authenticate the server. When working directly with sockets, use ssl.create_default_context() and its wrap_socket method with server_hostname set to the intended host name. Do not disable certificate or host-name verification. Higher-level HTTPS clients handle these details for you; the Python SSL/TLS certificates tutorial covers TLS sockets.

$ python get_request.py
HTTP/1.0 200 OK
Hello from HTTP!

Asynchronous echo server

The asyncio streams API provides a higher-level interface over non-blocking sockets. It lets a server handle multiple connections while waiting for network I/O, without creating a thread for every client. Stop the synchronous TCP server first; this server uses the same port, so echo_client.py works with it unchanged.

async_server.py
import asyncio


async def handle_client(reader, writer):
    peer = writer.get_extra_info('peername')
    print(f'Connected: {peer}', flush=True)
    try:
        while True:
            data = await reader.read(1024)
            if not data:
                break
            writer.write(data)
            await writer.drain()
    finally:
        writer.close()
        await writer.wait_closed()


async def main():
    server = await asyncio.start_server(handle_client, '127.0.0.1', 8001)
    async with server:
        print('Listening on 127.0.0.1:8001', flush=True)
        await server.serve_forever()


try:
    asyncio.run(main())
except KeyboardInterrupt:
    print('Server stopped')

The asyncio.run function manages the event loop. The server starts a handler coroutine for each connection and passes it a reader and a writer; get_extra_info('peername') returns the client address. The handler reads until end-of-stream just like the synchronous echo server. The drain call applies backpressure: it pauses writing when the outgoing buffer is too full, allowing a slow receiver to catch up. The finally block closes the writer even if the handler is cancelled or an I/O operation fails.

This server runs until interrupted and has no per-client timeout. Catching KeyboardInterrupt turns Ctrl+C into a short message instead of a traceback. A deployed service also needs idle timeouts, connection limits, and error handling. The output shows the server after the client from the next section has run and Ctrl+C was pressed; the client ports are chosen by the operating system and vary.

$ python async_server.py
Listening on 127.0.0.1:8001
Connected: ('127.0.0.1', 53506)
Connected: ('127.0.0.1', 53510)
Connected: ('127.0.0.1', 53524)
Server stopped

Concurrent asynchronous clients

To see the server handle several connections at once, the client opens three connections concurrently. Each one waits a second before sending, like a slow client.

async_client.py
import asyncio
import time


async def echo(name, delay):
    reader, writer = await asyncio.open_connection('127.0.0.1', 8001)
    try:
        await asyncio.sleep(delay)
        writer.write(f'Hello from {name}'.encode('utf-8'))
        await writer.drain()
        writer.write_eof()
        reply = await asyncio.wait_for(reader.read(), timeout=5)
        return reply.decode('utf-8')
    finally:
        writer.close()
        await writer.wait_closed()


async def main():
    start = time.perf_counter()
    replies = await asyncio.gather(
        echo('client 1', 1), echo('client 2', 1), echo('client 3', 1)
    )
    for reply in replies:
        print(reply)
    print(f'Elapsed: {time.perf_counter() - start:.1f} s')


asyncio.run(main())

The open_connection function returns a reader and writer pair, the client-side counterpart of start_server. The write_eof call is the stream version of the half-close, so reader.read() without a size reads until the server closes the connection. The wait_for function limits that wait to five seconds.

The gather function runs the three coroutines concurrently and returns their results in argument order. The three one-second delays overlap, both in the client and in the server, so the whole run takes about one second rather than three. Asynchronous I/O improves concurrency for waiting tasks; it does not make CPU-heavy work faster. See Python asyncio and Python async/await for the underlying concepts.

$ python async_client.py
Hello from client 1
Hello from client 2
Hello from client 3
Elapsed: 1.0 s

Source

The official documentation describes the socket methods, stream APIs, and protocol rules used in these examples.

In this article we resolved host names, exchanged bytes over TCP and UDP, framed messages with a length prefix, handled common socket errors, sent local HTTP requests, and built an asynchronous echo server with concurrent clients. For related topics, read the Python http.server, Python Requests, and Python asyncio tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.