Of course! Here is a comprehensive guide to Python's socket module, broken down into lists and explanations for easy understanding.
The socket module is Python's built-in interface to the Berkeley sockets API. It allows you to perform low-level network operations, like creating TCP/IP or UDP/IP clients and servers.
Key Socket Methods (A List of Core Functions)
This is the heart of the socket module. You'll use these methods to create and manage network connections.
For Both Clients and Servers
| Method |
Description |
Example |
socket.socket(family, type) |
Creates a new socket object. This is the first step for any network operation. |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
socket.gethostname() |
Returns the hostname of the machine where the Python interpreter is currently running. |
hostname = socket.gethostname() |
socket.gethostbyname(hostname) |
Returns the IP address of a given hostname. |
ip = socket.gethostbyname('www.google.com') |
For TCP Servers (Connection-Oriented)
| Method |
Description |
Example |
s.bind(address) |
Binds the socket to a specific address and port. The address is a tuple (ip, port). |
s.bind(('0.0.0.0', 65432)) |
s.listen(backlog) |
Puts the socket into listening mode. backlog is the number of unaccepted connections that the system will allow before refusing new connections. |
s.listen() |
s.accept() |
Accepts a new connection. It blocks until a client connects, then returns a new socket object to communicate with the client and the client's address. |
conn, addr = s.accept() |
For TCP Clients (Connection-Oriented)
| Method |
Description |
Example |
s.connect(address) |
Connects to a remote socket. The address is a tuple (ip, port). It will block until the connection is established or an error occurs. |
s.connect(('127.0.0.1', 65432)) |
For Data Transfer (Both Sides)
| Method |
Description |
Example |
s.sendall(data) |
Sends data to the connected socket. It continues to send data from the bytes object until all data has been sent or an error occurs. |
conn.sendall(b'Hello, world') |
s.recv(bufsize) |
Receives data from the socket. It blocks until data is available, returning up to bufsize bytes. |
data = conn.recv(1024) |
s.send(data) |
Sends data to the socket. It may not send all the data; you need to handle partial sends in a loop. (Use sendall for simplicity). |
s.send(b'Some data') |
s.close() |
Closes the socket. Releases the socket resource. |
conn.close() |
For UDP (Connectionless)
| Method |
Description |
Example |
s.sendto(data, address) |
Sends data to the socket at the given address. The address is a tuple (ip, port). |
s.sendto(b'Hello', ('127.0.0.1', 12345)) |
s.recvfrom(bufsize) |
Receives data and returns the data and the address of the sender. |
data, addr = s.recvfrom(1024) |
Socket Address Families (A List of Constants)
These constants define the protocol family to be used when creating a socket.
| Constant |
Description |
socket.AF_INET |
The most common family. It uses IPv4 addresses and standard TCP/UDP ports. The address tuple is (ip, port). |
socket.AF_INET6 |
The IPv6 equivalent of AF_INET. The address tuple is (ip, port, flow_info, scope_id). |
socket.AF_UNIX |
For communication between processes on the same host using a file system path. |
Socket Types (A List of Constants)
These constants define the type of socket.
| Constant |
Description |
socket.SOCK_STREAM |
TCP socket. Provides a reliable, connection-oriented, two-way communication stream. |
socket.SOCK_DGRAM |
UDP socket. Provides an unreliable, connectionless, message-oriented protocol. |
socket.SOCK_RAW |
Provides access to the underlying protocols, like ICMP. (Requires root/admin privileges). |
Common Socket Options (A List of setsockopt Flags)
You can control socket behavior using setsockopt. Here are some of the most common options.
| Option |
Description |
Example |
socket.SO_REUSEADDR |
Crucial for servers. Allows the reuse of an address/port combination that is in the TIME_WAIT state. This prevents "Address already in use" errors when quickly restarting a server. |
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
socket.SO_BROADCAST |
Allows the socket to send broadcast messages. |
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) |
Error Types (A List of Common Exceptions)
| Exception |
Description |
socket.error |
The base class for all socket-related errors. Other exceptions like gaierror and timeout are subclasses of it. |
socket.timeout |
Raised when a socket operation times out (e.g., settimeout has been called on the socket). |
socket.gaierror |
"getaddrinfo error". Raised for address-related errors, like a hostname that cannot be resolved. |
socket.ConnectionRefusedError |
A subclass of OSError. Raised when a connection is explicitly refused by the server (e.g., no process is listening on the port). |
Complete Code Examples
Simple TCP Server (Listens for one connection)
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
print(f"Server listening on {HOST}:{PORT}")
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
if not data:
break
print(f"Received from client: {data.decode('utf-8')}")
conn.sendall(data) # Echo the received data back to the client
Simple TCP Client (Connects, sends a message, and receives a reply)
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print(f'Received from server: {data.decode("utf-8")}')
Simple UDP Server (Receives a single datagram)
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 12345 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.bind((HOST, PORT))
print(f"UDP server listening on {HOST}:{PORT}")
data, addr = s.recvfrom(1024) # Buffer size is 1024 bytes
print(f"Received message from {addr}: {data.decode('utf-8')}")
Simple UDP Client (Sends a single datagram)
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 12345 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
message = b"Hello from UDP client!"
s.sendto(message, (HOST, PORT))
print(f"Sent message to {HOST}:{PORT}")