Ports, Sockets, and Connections
Port Numbers
A port is a 16-bit number (0–65535) that identifies a specific service on a machine. While an IP address identifies which machine, a port identifies which service on that machine.
- Well-known ports (0–1023): HTTP (80), HTTPS (443), SSH (22), DNS (53)
- Registered ports (1024–49151): PostgreSQL (5432), Redis (6379), MySQL (3306)
- Ephemeral ports (49152–65535): chosen automatically by the OS for outbound connections
Sockets
A socket is an endpoint for communication — identified by the tuple (protocol, local IP, local port, remote IP, remote port). For a TCP connection, the combination of these four values uniquely identifies a connection.
A server socket binds to a local IP and port (e.g., 0.0.0.0:8080) and listens for incoming connections. When a client connects, the OS creates a new socket for that specific connection, so the server can handle many clients simultaneously.
TCP Connection Lifecycle
Establishment: The Three-Way Handshake
- SYN — The client sends a packet with the SYN flag set, choosing an initial sequence number.
- SYN-ACK — The server acknowledges the client's SYN and sends its own SYN with its sequence number.
- ACK — The client acknowledges the server's SYN.
After the handshake, both sides know the other is ready and agree on initial sequence numbers.
Data Transfer
The client and server exchange data. TCP ensures:
- Reliability: lost packets are retransmitted (detected by missing ACKs or duplicate ACKs).
- Ordering: out-of-order packets are reassembled using sequence numbers.
- Flow control: the receiver advertises a window size to prevent buffer overflow.
- Congestion control: the sender adjusts its rate based on network conditions (e.g., TCP Reno, BBR).
Teardown: The Four-Way Handshake
- FIN — The initiator sends a FIN to close its side.
- ACK — The peer acknowledges the FIN.
- FIN — The peer sends its own FIN.
- ACK — The initiator acknowledges the peer's FIN.
This four-way handshake allows each direction to close independently (half-close). There is a 2 × MSL (maximum segment lifetime) wait at the end to ensure the final ACK is received and all delayed segments have expired.
Why Not Just Use IP Directly?
IP (the network-layer protocol) only provides best-effort delivery — it does not guarantee that a packet arrives, that it arrives only once, or that it arrives in order. TCP builds these guarantees on top of IP, which is why TCP connections are more expensive (handshake overhead, per-packet ACKs, retransmission buffers) but also more useful for applications that need reliability.