Ports & Sockets
IP delivers a packet to a host. But a host runs many programs at once: a browser, a mail client, an SSH session, a game. The transport layer adds port numbers so the operating system knows which program each packet belongs to.
Port numbers
A port is a 16-bit number (0–65535) in the TCP or UDP header. Every packet carries a source port and a destination port.
| Range | Name | Used for |
|---|---|---|
| 0–1023 | well-known (system) ports | standard services; binding them usually needs admin rights |
| 1024–49151 | registered ports | services registered with IANA (PostgreSQL 5432, …) |
| 49152–65535 | dynamic / ephemeral ports | picked by the OS for the client side of a connection |
WELL_KNOWN = {
20: ("TCP", "FTP data"), 21: ("TCP", "FTP control"), 22: ("TCP", "SSH"),
25: ("TCP", "SMTP"), 53: ("UDP/TCP", "DNS"), 67: ("UDP", "DHCP server"),
80: ("TCP", "HTTP"), 123: ("UDP", "NTP"), 143: ("TCP", "IMAP"),
443: ("TCP/UDP", "HTTPS (HTTP/3 over UDP)"), 3306: ("TCP", "MySQL"),
3389: ("TCP", "Remote Desktop"), 5432: ("TCP", "PostgreSQL"), 6379: ("TCP", "Redis"),
}
def category(port):
if port < 1024:
return "well-known"
if port < 49152:
return "registered"
return "ephemeral"
for port, (proto, service) in WELL_KNOWN.items():
print(f"{port:>5} {proto:<8} {service:<26} {category(port)}")
print(51514, category(51514)) 20 TCP FTP data well-known
21 TCP FTP control well-known
22 TCP SSH well-known
25 TCP SMTP well-known
53 UDP/TCP DNS well-known
67 UDP DHCP server well-known
80 TCP HTTP well-known
123 UDP NTP well-known
143 TCP IMAP well-known
443 TCP/UDP HTTPS (HTTP/3 over UDP) well-known
3306 TCP MySQL registered
3389 TCP Remote Desktop registered
5432 TCP PostgreSQL registered
6379 TCP Redis registered
51514 ephemeral
Note: A port number is a convention, not a guarantee. Nothing stops someone running SSH on port 443 or a web server on 8080. Firewalls that "allow port 443" allow whatever is listening there.
Sockets and the 5-tuple
A socket is the operating system's handle for one end of a communication. A server has a listening socket bound to an address and port, for example 0.0.0.0:443 (all interfaces). Each accepted TCP connection gets its own socket.
A TCP connection is uniquely identified by the 5-tuple: protocol, source IP, source port, destination IP, destination port. That's how one web server on port 443 can talk to thousands of clients at once: every client connection differs in at least one field.
connections = [
("tcp", "192.168.1.20", 51514, "93.184.215.14", 443),
("tcp", "192.168.1.20", 51515, "93.184.215.14", 443), # second tab, new source port
("tcp", "10.8.0.6", 51514, "93.184.215.14", 443), # another client, same port
("udp", "192.168.1.20", 51514, "93.184.215.14", 443), # QUIC: different protocol
]
print("distinct connections:", len(set(connections)))
# The server demultiplexes incoming segments by looking up the 5-tuple.
sockets = {c: f"socket #{i}" for i, c in enumerate(connections, start=3)}
incoming = ("tcp", "10.8.0.6", 51514, "93.184.215.14", 443)
print("segment from 10.8.0.6:51514 goes to", sockets[incoming])distinct connections: 4
segment from 10.8.0.6:51514 goes to socket #5
Ephemeral ports
When a client connects, the OS picks a free source port from the ephemeral range. On Linux the range is configurable and by default is 32768–60999:
class PortAllocator:
def __init__(self, low, high):
self.low, self.high = low, high
self.next = low
self.in_use = set()
def allocate(self):
for _ in range(self.high - self.low + 1):
port = self.next
self.next = self.low if port == self.high else port + 1
if port not in self.in_use:
self.in_use.add(port)
return port
raise OSError("Cannot assign requested address (ports exhausted)")
def release(self, port):
self.in_use.discard(port)
ports = PortAllocator(60995, 60999) # a tiny range to show exhaustion
opened = [ports.allocate() for _ in range(5)]
print("opened:", opened)
try:
ports.allocate()
except OSError as err:
print("error:", err)
ports.release(60997)
print("after closing one:", ports.allocate())
print("default Linux range size:", 60999 - 32768 + 1)opened: [60995, 60996, 60997, 60998, 60999]
error: Cannot assign requested address (ports exhausted)
after closing one: 60997
default Linux range size: 28232
Port exhaustion is a real production problem: a busy proxy opening many short connections to the same backend can run out of source ports, because closed connections linger in the TIME_WAIT state for a while.
Socket constants
Python's socket module exposes the same constants as the C socket API. These are just numbers; using them doesn't touch the network:
import socket
print("AF_INET =", int(socket.AF_INET), "(IPv4)")
print("AF_INET6 =", int(socket.AF_INET6), "(IPv6)")
print("SOCK_STREAM =", int(socket.SOCK_STREAM), "(TCP: reliable byte stream)")
print("SOCK_DGRAM =", int(socket.SOCK_DGRAM), "(UDP: datagrams)")
print("IPPROTO_TCP =", socket.IPPROTO_TCP, " IPPROTO_UDP =", socket.IPPROTO_UDP)
print(socket.htons(443), "<- 443 in network byte order, read as a little-endian number")AF_INET = 2 (IPv4)
AF_INET6 = 10 (IPv6)
SOCK_STREAM = 1 (TCP: reliable byte stream)
SOCK_DGRAM = 2 (UDP: datagrams)
IPPROTO_TCP = 6 IPPROTO_UDP = 17
47873 <- 443 in network byte order, read as a little-endian number
htons ("host to network short") swaps the two bytes on little-endian machines. You'll rarely call it from Python, but you'll see it in every C networking example.
Listing sockets on your machine
ss -tulpnSample output:
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
udp UNCONN 0 0 127.0.0.53%lo:53 0.0.0.0:* users:(("systemd-resolve",pid=612,fd=13))
tcp LISTEN 0 4096 127.0.0.1:5432 0.0.0.0:* users:(("postgres",pid=1043,fd=7))
tcp LISTEN 0 511 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=1101,fd=6))
tcp LISTEN 0 128 [::]:22 [::]:* users:(("sshd",pid=880,fd=4))-t TCP, -u UDP, -l listening only, -p show the process, -n numeric ports. Note PostgreSQL is bound to 127.0.0.1: only programs on the same machine can reach it. Binding to 0.0.0.0 exposes a service on every interface, a common accidental security hole. On Windows use netstat -ano.
Test yourself
Which five values uniquely identify a TCP connection?
- Source and destination MAC, IP and TTL
- Protocol, source IP, source port, destination IP, destination port
- Hostname, port, protocol, time, sequence
- Only the destination IP and port
What port does HTTPS use by default?
- 80
- 443
- 8080
- 22
A server is bound to 127.0.0.1:5432. Who can connect to it?
- Anyone on the Internet
- Anyone on the LAN
- Only programs on the same machine
- Nobody