← All chapters
Chapter 28· 7 min read · illustrated

Ports & Sockets

How one machine runs many services — and what a "connection" really is

We have used ports throughout the course; now let’s make them precise. Ports are how a single IP hosts many services at once, and a socket is the exact endpoint of a connection. These two ideas quietly underpin all networked software.

01

Ports are doors on a machine

A single machine has one IP but runs many programs that need the network. A port number (0–65535) identifies which program a packet is for. Think of the IP as the building’s street address and ports as the numbered doors inside.

Tap to enlarge
02

Well-known ports

Common services use standard, memorized ports so clients know where to knock:

22
SSH
53
DNS
80 / 443
HTTP / HTTPS
5432
PostgreSQL
Tap to enlarge
03

Port ranges

The 65,536 ports are split into ranges: 0–1023 are well-known (reserved for standard services), 1024–49151 are registered, and 49152+ are ephemeral — temporary ports the OS assigns to your outbound connections as the source port.

Tap to enlarge
04

A socket = IP + port

A socket is the combination of an IP address and a port — for example 10.0.0.1:443. It is the precise endpoint of communication. When your code "opens a socket", it is claiming one of these endpoints to send or receive on.

Tap to enlarge
05

A connection is a 4-tuple

One connection is uniquely identified by two sockets: (source IP, source port, destination IP, destination port) — the 4-tuple from Chapter 1. This is why your browser can hold many simultaneous connections to the same server: each uses a different source port, so each 4-tuple is unique.

Tap to enlarge
06

Public vs private IP (recap)

Tying it back: inside your network, devices use private IPs (192.168.x.x) and any local ports they like. To the outside world, NAT maps them onto the router’s single public IP using ports to keep the connections apart — ports and sockets are exactly what make that sharing possible.

Tap to enlarge