Sub topic 2
Ports, sockets and multiplexing
This chapter assumes you know the four-layer model (application, transport, network, link), what an IP address and a packet are, and basic Python. It covers how the transport layer lets many programs on one host share a single IP address, and how the operating system decides which program receives each arriving packet.
Why IP addresses are not enough
IP delivers a packet to a host. A host runs many programs at once: a browser with several tabs, a mail client, a DNS resolver, an SSH session. The IP header has no field saying which program should get the payload.
The transport layer fills that gap with ports. A port is a 16-bit unsigned number (0 to 65535) carried in the header of every TCP segment and UDP datagram. Each transport header has a source port and a destination port. Together with the IP addresses, they name the two endpoints of a conversation.
- Multiplexing is the sending side's job. Many programs hand data to the transport layer, and each piece leaves stamped with its own port numbers.
- Demultiplexing is the receiving side's job. The transport layer reads the port numbers in each arriving packet and hands the payload to the right program.
A port number has no meaning outside its host and protocol. Port 80 on one server is unrelated to port 80 on another, and TCP port 53 is a different resource from UDP port 53.
Port ranges
IANA, the registry that assigns port numbers, divides the space into three ranges.
| Range | Name | Typical use |
|---|---|---|
| 0–1023 | Well-known (system) ports | Standard services: 22 SSH, 25 SMTP, 53 DNS, 80 HTTP, 443 HTTPS |
| 1024–49151 | Registered ports | Applications registered with IANA, such as 5432 for PostgreSQL |
| 49152–65535 | Dynamic (ephemeral) ports | Temporary client-side ports |
Two practical points follow from this table.
- On Unix-like systems, binding to a port below 1024 normally requires elevated privileges. A permission error ("Permission denied") when starting a server on port 80 usually means this.
- The ephemeral range is a convention, not a law. Linux defaults to 32768–60999, which you can read from
/proc/sys/net/ipv4/ip_local_port_range. Windows and recent BSDs follow the IANA range.
Sockets: the program's handle on a port
A socket is the operating system object that a program uses to send and receive data over the network. In the sockets API you create one with socket(). It becomes useful once it is associated with a local address and port.
A port and a socket are different things. A port is a number in a header. A socket is a kernel object, and the kernel keeps a table that maps header values to sockets. Several sockets can be tied to the same local port number, as the TCP section below shows.
An endpoint is an IP address plus a port, often written 192.0.2.10:443. A transport conversation is identified by five values, the 5-tuple:
- Protocol (TCP or UDP)
- Source IP
- Source port
- Destination IP
- Destination port
Binding and ephemeral ports
A server calls bind() to claim a specific local address and port, so that clients know where to send traffic. A client usually does not bind. When it calls connect() (TCP) or first calls sendto() (UDP), the kernel picks an unused ephemeral port as the source port.
Binding to port 0 asks the kernel to choose any free port. You then read the choice back with getsockname(). This is useful in tests, where a fixed port might already be taken.
The address you bind to matters.
127.0.0.1accepts only connections from the same machine (the loopback interface).0.0.0.0accepts traffic arriving on any IPv4 address of the host.- A specific interface address accepts traffic only for that address.
A server that works from your laptop but is unreachable from another machine is often bound to 127.0.0.1 by mistake.
How the kernel demultiplexes
UDP and TCP use different lookup keys.
UDP: destination only
A UDP socket is normally identified by its local IP and port. A datagram addressed to 192.0.2.10:5353 goes to whichever socket is bound there, regardless of who sent it. One UDP socket can therefore receive datagrams from thousands of different senders, and recvfrom() tells you which sender each came from.
TCP: the full 4-tuple
TCP is connection-oriented, so the kernel tracks each connection separately. It matches an arriving segment against the source IP, source port, destination IP and destination port. Two clients connecting to the same server port produce two different connections, even though both target the same destination port.
A TCP server uses two kinds of socket.
- The listening socket is bound to the server port and only waits for new connections. It never carries application data.
- Each call to
accept()returns a new connected socket. It has the same local port as the listener but is tied to one specific remote IP and port.
The next diagram shows one listener and two connected sockets sharing port 443.
Note that clients A and B use the same source port, 50001. That is fine, because their source IPs differ and the 4-tuples are different. The server's capacity is not limited to 64K connections, since the limit applies to each unique client IP and port pair, not to the server port.
Seeing it in code
This script starts a TCP server on a kernel-chosen port, connects two clients, and prints the addresses from each side. Both server-side connected sockets show the same local port, and each client has a different ephemeral port.
import socket
import threading
ready = threading.Event()
def server(port_holder):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
srv.bind(("127.0.0.1", 0))
port_holder.append(srv.getsockname()[1])
srv.listen()
ready.set()
for _ in range(2):
conn, addr = srv.accept()
with conn:
print("server side:", conn.getsockname(), "<-", conn.getpeername())
ports = []
t = threading.Thread(target=server, args=(ports,))
t.start()
ready.wait()
clients = [socket.create_connection(("127.0.0.1", ports[0])) for _ in range(2)]
for c in clients:
print("client side:", c.getsockname(), "->", c.getpeername())
t.join()
for c in clients:
c.close()Run it and compare the output lines. The server prints the same local port twice with two different peer ports. The exact port numbers differ on every run, and the lines from the two threads may interleave.
One port number, two protocols
TCP and UDP keep separate port tables. A UDP socket and a TCP socket can both be bound to the same number at once. Two UDP sockets cannot, unless special options are set.
import socket
udp1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp1.bind(("127.0.0.1", 0))
port = udp1.getsockname()[1]
udp2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
udp2.bind(("127.0.0.1", port))
except OSError as err:
print("second UDP bind failed:", err.strerror)
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp.bind(("127.0.0.1", port))
print("TCP bind on the same port number worked:", port)
for s in (udp1, udp2, tcp):
s.close()The second UDP bind fails with "Address already in use", and the TCP bind succeeds. This is why DNS servers listen on both UDP 53 and TCP 53 as two independent services.
Common errors
| Symptom | Likely cause |
|---|---|
| `Address already in use` when restarting a server | An earlier socket on that port is still held by the OS, often a TCP connection in TIME_WAIT or another process. For TCP servers, set `SO_REUSEADDR` before `bind()`. |
| `Permission denied` on bind | Port below 1024 without privileges. Use a higher port or a reverse proxy. |
| `Connection refused` (TCP) | No socket is listening on that destination port, so the host replies with a reset (RST). |
| UDP client hangs or times out | No socket is bound on the destination port. The host may send an ICMP "port unreachable" message, but UDP gives no guarantee you will see it, so always set a timeout. |
| Server reachable locally but not remotely | Bound to `127.0.0.1` instead of `0.0.0.0` or the public address. |
| Client fails to connect under heavy load | Ephemeral ports exhausted. Many short connections to the same destination can use up the range, particularly while closed connections sit in TIME_WAIT. |
Inspecting ports on a real machine
On Linux, ss -tulpn lists listening TCP and UDP sockets with the owning process. ss -tn lists established TCP connections as local and remote endpoint pairs, which are the 4-tuples described above. On macOS, lsof -i -P -n gives similar information. When a port conflict stops a server from starting, this is the first place to look.
NAT and the 5-tuple
A NAT (network address translation) device, such as a home router, rewrites source addresses and ports so that many private hosts share one public IP. It keeps its own table that maps each private 5-tuple to a public one. Port numbers are what let the NAT tell the conversations apart. This is also why unsolicited inbound traffic is dropped: no table entry exists for it.
Exercise
A web server listens on TCP port 443. Two browser tabs on the same laptop (IP 198.51.100.7) each open a connection to it. How can the server tell the two connections apart, and how many listening sockets and connected sockets does it hold for them?
Show answer
The two connections have the same source IP and destination IP and port, but the browser picked a different ephemeral source port for each tab, so their 4-tuples differ and the kernel delivers segments to the right socket. The server holds one listening socket on port 443 and two connected sockets, one per connection, both with local port 443.
Exercise
You start a UDP server on port 5000 and, in another terminal, a second UDP server on port 5000 on the same address. The second one fails. You then start a TCP server on port 5000, and it works. Explain both results.
Show answer
The kernel keeps separate port tables for UDP and TCP, so the protocol is part of the lookup key. Two UDP sockets cannot both own the same local address and port because a datagram is demultiplexed only by destination address and port, which would make delivery ambiguous. A TCP socket on the same number does not conflict because it lives in the TCP table.