socket
import socket The socket module is Python’s interface to the BSD socket API, available on all modern Unix systems, Windows, macOS, and most other platforms. It provides the foundation for network communication in Python, enabling you to create both TCP clients and servers, UDP datagram communication, and more specialized socket types.
The module exposes socket families (like AF_INET for IPv4 and AF_UNIX for Unix domain sockets), socket types (SOCK_STREAM for TCP and SOCK_DGRAM for UDP), and functions to create and manipulate sockets. The socket() function returns a socket object whose methods implement the various socket system calls.
Creating Sockets
socket()
The primary function for creating sockets. Returns a new socket object using the specified address family, socket type, and protocol.
socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
family | int | AF_INET | Address family (e.g., AF_INET, AF_INET6, AF_UNIX) |
type | int | SOCK_STREAM | Socket type (SOCK_STREAM for TCP, SOCK_DGRAM for UDP) |
proto | int | 0 | Protocol number (usually zero, auto-selected) |
fileno | int | None | Existing file descriptor to wrap (auto-detects family/type/proto) |
Returns: A socket.socket object.
socketpair()
Creates a pair of connected socket objects. Useful for inter-process communication or testing.
socket.socketpair(family=None, type=SOCK_STREAM, proto=0)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
family | int | AF_UNIX (or AF_INET if unavailable) | Address family for the sockets |
type | int | SOCK_STREAM | Socket type |
proto | int | 0 | Protocol number |
Returns: A tuple of two connected socket.socket objects.
create_server()
Creates a server socket bound to an address. A convenience function introduced in Python 3.8 that simplifies the common pattern of creating a listening TCP socket.
socket.create_server(address, *, family=AF_INET, backlog=None, reuse_port=False, dualstack_ipv6=False)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
address | tuple | — | A 2-tuple (host, port) to bind to |
family | int | AF_INET | Address family (AF_INET or AF_INET6) |
backlog | int | None | Queue size for listen() (system default if None) |
reuse_port | bool | False | Enable SO_REUSEPORT option |
dualstack_ipv6 | bool | False | Accept both IPv4 and IPv6 connections on IPv6 sockets |
Returns: A socket.socket object bound to the address and ready to accept connections.
fromfd()
Creates a socket object from an existing file descriptor.
socket.fromfd(fd, family, type, proto=0)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
fd | int | — | Open file descriptor to wrap |
family | int | — | Address family |
type | int | — | Socket type |
proto | int | 0 | Protocol number |
Returns: A socket.socket object wrapping the file descriptor.
Timeout Functions
setdefaulttimeout()
Sets the default timeout for newly created socket objects.
socket.setdefaulttimeout(timeout)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
timeout | float | — | Timeout in seconds (None for no timeout) |
getdefaulttimeout()
Returns the current default timeout for new socket objects.
socket.getdefaulttimeout()
Returns: The default timeout in seconds as a float, or None if no timeout is set.
Address Families
| Constant | Description |
|---|---|
AF_INET | IPv4 addresses (host, port) pairs |
AF_INET6 | IPv6 addresses (host, port, flowinfo, scope_id) tuples |
AF_UNIX | Unix domain sockets (file system paths) |
AF_CAN | Controller Area Network (Linux) |
AF_PACKET | Raw packet interface (Linux) |
Socket Types
| Constant | Description |
|---|---|
SOCK_STREAM | Oriented to reliable TCP connections |
SOCK_DGRAM | Datagram-oriented UDP connections |
SOCK_RAW | Raw socket (bypasses protocol layers) |
SOCK_SEQPACKET | Sequenced packet socket |
Examples
TCP server with create_server()
import socket
with socket.create_server(('0.0.0.0', 9000), backlog=5) as server:
print("Server listening on port 9000")
conn, addr = server.accept()
print(f"Connection from {addr}")
data = conn.recv(1024)
print(f"Received: {data}")
conn.sendall(b"Hello from server")
conn.close()
Server listening on port 9000
Connection from ('127.0.0.1', 54321)
Received: b'Hello client'
Using socketpair() for inter-process communication
import socket
# Create a connected pair of sockets
client, server = socket.socketpair()
# Send data from client to server
client.send(b"Hello from the other end!")
data = server.recv(1024)
print(f"Server received: {data}")
# Clean up
client.close()
server.close()
Server received: b'Hello from the other end!'
UDP datagram socket
import socket
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('127.0.0.1', 9001))
# Receive a datagram
data, addr = sock.recvfrom(1024)
print(f"Received from {addr}: {data}")
# Send a response
sock.sendto(b"Ack: " + data, addr)
sock.close()
Received from ('127.0.0.1', 54322): b'Test message'
Common Patterns
Setting a timeout on individual sockets
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5.0) # 5 second timeout
sock.connect(('example.com', 80))
Using getdefaulttimeout() for consistent behavior
import socket
# Set default timeout for all new sockets
socket.setdefaulttimeout(10.0)
# Now all new sockets inherit this timeout
sock1 = socket.socket() # has 10s timeout
sock2 = socket.socket() # also has 10s timeout
Reusing addresses with SO_REUSEPORT
import socket
# Using create_server with reuse_port
server = socket.create_server(
('0.0.0.0', 8000),
reuse_port=True
)
Errors
The socket module raises several exceptions for different error conditions:
-
socket.error— Deprecated alias forOSError. Raised for general socket errors (e.g., connection refused, network unreachable). -
socket.timeout— Deprecated alias forTimeoutError. Raised when a socket operation times out. -
socket.gaierror— Subclass ofOSError. Raised for DNS-related errors fromgetaddrinfo()andgetnameinfo(). -
socket.herror— Subclass ofOSError. Raised for host-related errors fromgethostbyname()andgethostbyaddr().
All socket-related errors are subclasses of OSError, so you can catch them with a single except OSError clause.