Socket Module
TL;DR
The socket module provides low-level access to BSD sockets for network programming. It supports TCP and UDP protocols across IPv4 and IPv6, offering both connection-oriented and connectionless communication patterns for building custom network applications.
Interesting!
The socket module includes sendfile() for zero-copy file transmission, which bypasses userspace buffering and can be significantly faster than reading a file and calling send() in a loop. This is particularly useful for web servers and file transfer applications.
Creating Sockets
The socket() function creates a socket object. You specify the address family (usually AF_INET for IPv4) and socket type (SOCK_STREAM for TCP or SOCK_DGRAM for UDP).
python code snippet start
import socket
# TCP socket (connection-oriented)
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# UDP socket (connectionless)
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# IPv6 TCP socket
ipv6_socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)python code snippet end
Sockets support context managers for automatic cleanup:
python code snippet start
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(('example.com', 80))
s.send(b'GET / HTTP/1.0\r\n\r\n')
response = s.recv(4096)
# Socket automatically closedpython code snippet end
TCP Client-Server Communication
TCP sockets provide reliable, ordered, connection-oriented communication. The server binds to an address, listens for connections, and accepts clients.
python code snippet start
# TCP Server
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('localhost', 5000))
server.listen(5) # Queue up to 5 connections
print("Server listening on port 5000")
conn, addr = server.accept() # Blocks until client connects
print(f"Connected by {addr}")
data = conn.recv(1024)
print(f"Received: {data.decode()}")
conn.sendall(b'Message received')
conn.close()
server.close()python code snippet end
The client connects to the server’s address and exchanges data:
python code snippet start
# TCP Client
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 5000))
client.sendall(b'Hello, server!')
response = client.recv(1024)
print(f"Server says: {response.decode()}")
client.close()python code snippet end
UDP Communication
UDP sockets are connectionless and don’t require connect(), listen(), or accept(). Instead, use sendto() and recvfrom() which include address information.
python code snippet start
# UDP Server
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(('localhost', 5001))
print("UDP server listening on port 5001")
data, addr = server.recvfrom(1024) # Returns (data, address)
print(f"Received from {addr}: {data.decode()}")
server.sendto(b'ACK', addr)
server.close()python code snippet end
And at the client end:
python code snippet start
# UDP Client
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(b'UDP message', ('localhost', 5001))
data, addr = client.recvfrom(1024)
print(f"Response: {data.decode()}")
client.close()python code snippet end
UDP is faster but doesn’t guarantee delivery, ordering, or duplicate prevention. It’s ideal for streaming, gaming, or situations where speed matters more than reliability.
Helper Functions and Utilities
The socket module provides convenience functions that handle common networking tasks:
python code snippet start
# Get your local hostname
hostname = socket.gethostname()
# Resolve hostname to IP address
ip = socket.gethostbyname('python.org')
# Get detailed address information (returns list of tuples)
addr_info = socket.getaddrinfo('python.org', 443, socket.AF_INET, socket.SOCK_STREAM)
# Each tuple: (family, type, proto, canonname, sockaddr)
# Create a connection to a TCP service (higher-level)
conn = socket.create_connection(('python.org', 443), timeout=10)
conn.close()
# Create a server socket (higher-level, Python 3.8+)
server = socket.create_server(('localhost', 8000))
server.listen()
conn, addr = server.accept()python code snippet end
For IP address conversion:
python code snippet start
# IPv4 string to binary
packed = socket.inet_aton('192.168.1.1') # Returns 4-byte binary
# Binary to IPv4 string
ip = socket.inet_ntoa(packed) # Returns '192.168.1.1'
# Works with IPv6 too
ipv6_packed = socket.inet_pton(socket.AF_INET6, '2001:db8::1')
ipv6_str = socket.inet_ntop(socket.AF_INET6, ipv6_packed)python code snippet end
Timeouts and Operating Modes
Sockets operate in three modes: blocking (default), non-blocking, and timeout mode.
python code snippet start
import socket
s = socket.socket()
# Blocking mode (default) - operations wait indefinitely
s.setblocking(True)
# Non-blocking mode - operations fail immediately if not ready
s.setblocking(False)
# Timeout mode - operations fail after timeout seconds
s.settimeout(5.0) # 5 seconds
try:
s.connect(('python.org', 443))
except socket.timeout:
print("Connection timed out")python code snippet end
Set a global default timeout for all new sockets:
python code snippet start
socket.setdefaulttimeout(10.0) # 10 seconds for all new socketspython code snippet end
Error Handling
Socket operations raise OSError or its subclasses:
python code snippet start
import socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
s.connect(('unreachable.example.com', 80))
except socket.timeout:
print("Connection timed out")
except socket.gaierror as e:
print(f"Address resolution error: {e}")
except OSError as e:
print(f"Socket error: {e}")
finally:
s.close()python code snippet end
Common exceptions:
socket.timeout: Operation exceeded timeoutsocket.gaierror:getaddrinfo()and related errorsOSError: General socket errors (connection refused, address in use, etc.)
The socket module provides the foundation for network communication in Python. For higher-level protocols like HTTP, consider using libraries like urllib, requests, or httpx. For async programming, the asyncio module provides non-blocking socket operations.
The urllib module builds on socket for HTTP operations. For a more elegant HTTP interface, see http.client and Requests . The asyncio module provides high-level async networking.
Reference: socket — Low-level networking interface