Opscraft
TCP vs UDP · Lesson 1 of 8 · 3 min read

The transport layer: ports and sockets

TCP and UDP are the two transport protocols (layer 4) that almost all traffic rides on. TCP gives applications a reliable, ordered byte stream at the cost of handshakes, acknowledgements and congestion control; UDP sends independent datagrams and leaves reliability to the application. Senior interviews go past "TCP is reliable, UDP is fast": they ask how TCP achieves reliability and why packet loss hurts throughput so much, why DNS uses both, why HTTP/3 moved to UDP, how load balancers and NAT treat each protocol, and how to diagnose transport-level problems in production.

What layer 4 adds

IP delivers packets between hosts. The transport layer delivers data between processes on those hosts by adding port numbers (16-bit, 0–65535):

Range Name Examples
0–1023 Well-known (system) ports — binding needs root/CAP_NET_BIND_SERVICE on Linux 22, 53, 80, 443
1024–49151 Registered ports 3306, 5432, 6379, 8080, 9092
49152–65535 Dynamic/private (IANA's ephemeral range) Client source ports

Linux's default ephemeral port range for outgoing connections is 32768–60999 (net.ipv4.ip_local_port_range) — about 28,000 ports per destination IP:port tuple.

Enlarge diagram0-1023 well-known1024-49151 registered (3306, 5432, 8080…)49152-65535Linux ephemeral range 32768-60999 (~28,000 ports)Ports below 1024 need root or CAP_NET_BIND_SERVICE to listen on.
Figure 1. The 65,536 port numbers. Servers listen on well-known or registered ports; clients get a temporary (ephemeral) port for each outgoing connection.
Swipe sideways to see all of it, or tap to open it full screen.

Sockets and connections

  • A socket is an endpoint: IP + port + protocol.
  • A TCP connection is uniquely identified by the 5-tuple: protocol, source IP, source port, destination IP, destination port. One server port (443) can therefore serve hundreds of thousands of clients — each connection differs in client IP/port.
  • A client making many short-lived connections to the same destination can exhaust its ephemeral ports → Cannot assign requested address (EADDRNOTAVAIL). Fix with connection pooling/keep-alive, a wider port range, or tcp_tw_reuse.
Enlarge diagramserver10.0.0.5 : 443client A10.1.1.7 : 51022client A again10.1.1.7 : 51023client B10.1.4.2 : 40511TCP · 10.1.1.7 : 51022 → 10.0.0.5:443TCP · 10.1.1.7 : 51023 → 10.0.0.5:443TCP · 10.1.4.2 : 40511 → 10.0.0.5:443
Figure 2. One server port serves many clients because each connection is identified by all five values: protocol, source IP, source port, destination IP, destination port.
Swipe sideways to see all of it, or tap to open it full screen.