Topic 2.1
Ports, Sockets & Connections
In one line
A port identifies a program on a host; a connection is uniquely identified by five values: protocol, source IP, source port, destination IP, destination port.
Think of it like this
An office building (IP address) with numbered apartments (ports). A letter needs both the building address and the apartment number to reach the right person.
Key ideas
- 01
Ports are 16-bit numbers (0–65535). WELL-KNOWN ports (0–1023) are for standard services: 22 SSH, 53 DNS, 80 HTTP, 443 HTTPS. REGISTERED ports (1024–49151) are for applications: 5432 Postgres, 6379 Redis, 9092 Kafka, 3306 MySQL. EPHEMERAL ports (Linux default 32768–60999) are picked automatically for the CLIENT side of outgoing connections.
- 02
A SOCKET is an endpoint (IP + port) a program reads from and writes to. A server LISTENS on a socket; each client connection creates a new connected socket on the server, all sharing the same listening port. That's how one web server on port 443 handles thousands of connections.
- 03
The 5-TUPLE (protocol, src IP, src port, dst IP, dst port) uniquely identifies a connection. Load balancers hash it, firewalls match on parts of it, and the NAT table on a NAT gateway (AWS course, Topic 3.2) tracks it.
- 04
Binding to ports below 1024 traditionally requires root on Linux, one reason containers listen on 8080 and the load balancer or container runtime maps 80/443 to it (Docker course, Topic 4.2).
Code & diagrams
ss -ltnp # listening TCP sockets with the owning process
ss -tn state established # current established connections (5-tuples)
cat /proc/sys/net/ipv4/ip_local_port_range # ephemeral port range: 32768 60999
sudo lsof -i :5432 # who is using port 5432?Explain it without notes
How can one web server on port 443 serve 10,000 clients at the same time?
Practice
A service makes many short-lived outbound connections to the same database IP and port. Why might it run out of ephemeral ports, and roughly how many can it have open to that single destination?
Trade-offs
- ↔
Well-known ports make services discoverable but invite automated scanning; non-standard ports reduce noise but aren't security. Access control belongs in firewalls and authentication.
Done when you can
I know the common ports for SSH, DNS, HTTP(S), Postgres, Redis, and Kafka.
I can explain listening vs connected sockets and the 5-tuple.
I can find which process owns a port.