Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Standard Library: Concurrency, Network and Tools

The socket module

Reference for Python's socket module: TCP clients and servers, UDP, bind, listen, accept, connect, recv, sendall, timeouts, socketpair and address helpers.

The socket module is Python's interface to the operating system's network sockets. A socket is one end of a connection: you create it, connect it (client) or bind and listen on it (server), then send and receive bytes. Everything higher up, from HTTP to email, is built on this.

Sockets move bytes, not text, and TCP is a stream: one send() on one side does not guarantee one matching recv() on the other. Real protocols add their own framing, such as a length prefix or a newline.

Python
import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect(("example.com", 80))
    s.sendall(b"HEAD / HTTP/1.0\r\n\r\n")
    print(s.recv(200))

Try it

The browser sandbox has no network and cannot open sockets, so these examples use only helpers that run offline. The client and server code further down is read-only.

Python Addresses, byte order and parsing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python A socket without a network

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A TCP echo server and client for your own machine (read-only):

Python
import socket
import threading

def serve(listener):
    conn, addr = listener.accept()
    with conn:
        data = conn.recv(1024)
        conn.sendall(data.upper())

listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", 0))          # port 0: the OS picks a free port
listener.listen()
port = listener.getsockname()[1]
threading.Thread(target=serve, args=(listener,), daemon=True).start()

with socket.create_connection(("127.0.0.1", port), timeout=5) as client:
    client.sendall(b"hello")
    print(client.recv(1024))             # b'HELLO'
listener.close()

Syntax

Python
socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0)
socket.create_connection(address, timeout=..., source_address=None)
socket.create_server(address, *, family=AF_INET, backlog=None, reuse_port=False)
Name Description
family Address family: AF_INET (IPv4), AF_INET6 (IPv6) or AF_UNIX (local, Unix only).
type SOCK_STREAM for TCP, SOCK_DGRAM for UDP.
address A (host, port) tuple for IP sockets.

Key socket methods:

Method Description
bind(address), listen(backlog), accept() Server side. accept() returns (new_socket, client_address).
connect(address) Client side.
send(data), sendall(data) send may send only part of the data and returns the count; sendall keeps going until everything is sent.
recv(bufsize) Receives up to bufsize bytes. An empty bytes object means the peer closed the connection.
sendto(data, address), recvfrom(bufsize) UDP datagrams.
settimeout(seconds) Makes blocking calls raise TimeoutError after the given time.
setsockopt(level, option, value) Sets options such as SO_REUSEADDR.
shutdown(how), close() Ends one or both directions; frees the socket.

Raises: OSError and its subclasses (ConnectionRefusedError, TimeoutError, ConnectionResetError, socket.gaierror for name lookup failures).

Usage notes

  • Use with (sockets are context managers) or close() so the descriptor is released.
  • Loop on recv(). One call may return only part of a message. Read until you have a full frame, or until b"" arrives.
  • Prefer sendall() for ordinary sends; plain send() can quietly send less than you asked.
  • Always set a timeout on clients. Without one, a stuck server blocks you forever.
  • SO_REUSEADDR lets a server restart right away instead of failing with "address already in use".
  • Binding to 127.0.0.1 keeps a server private to your machine; 0.0.0.0 listens on every interface.
  • Names versus IPs. socket.getaddrinfo() resolves a host to every usable address and family; gethostbyname() handles only IPv4.
  • Blocking by default. For many connections use selectors, threads, or asyncio instead of one blocking loop.
  • Encryption is not part of this module. Wrap a socket with the ssl module, or use a library, for HTTPS.
  • Not usable in Pyodide or other sandboxes without network access.