Cheat SheetsComputer NetworksTransport Layer

Transport Layer — Cheat Sheet

Computer Networks · 5 topics. Download the PDF or the Instagram carousel and share it.

Cheat Sheet · AiCanCode.org
Transport Layer
Computer Networks5 topicsQuick revision reference
1

TCP 3-Way Handshake

TCP establishes a reliable connection using a 3-way handshake (SYN → SYN-ACK → ACK) before any data is exchanged, and closes it with a 4-way FIN sequence.

  • TCP handshake: SYN → SYN-ACK → ACK. Costs 1 RTT before data flows.
  • Sequence numbers synchronised during handshake enable ordered, reliable delivery.
  • Teardown is 4-way (FIN/ACK/FIN/ACK) because each direction closes independently.
  • TIME_WAIT lasts ~60–120s; high connection rates can exhaust ephemeral ports.
  • CLOSE_WAIT lingering usually means the application is not closing its sockets.
  • Connection pooling amortises handshake cost — essential for databases, HTTP, and Redis clients.
TCP 3-way handshake flow and Java socket
// TCP 3-Way Handshake:
//
// Client                          Server
//   │                                │
//   │──── SYN (seq=x) ──────────────>│  Client picks random ISN x
//   │                                │  Server receives, picks ISN y
//   │<─── SYN-ACK (seq=y, ack=x+1) ─│  Server acks client's ISN
//   │                                │
//   │──── ACK (ack=y+1) ────────────>│  Client acks server's ISN
//   │                                │
//   │══════ Connection ESTABLISHED ══│
//   │──── HTTP GET /api/users ──────>│  Data can now flow

// In Java — the handshake is invisible but implicit:
Socket socket = new Socket("api.example.com", 443);
// ↑ This line triggers the full 3-way handshake before returning
// The OS TCP stack handles SYN/SYN-ACK/ACK transparently

// Cost: 1 RTT before first byte of data
// On a 100ms RTT link, every new TCP connection costs 100ms upfront
2

TCP Flow & Congestion Control

TCP flow control prevents the sender from overwhelming the receiver; congestion control prevents the sender from overwhelming the network — both use sliding windows to regulate data rate.

  • Flow control: receiver advertises rwnd; sender cannot exceed it. Protects receiver buffer.
  • Congestion control: sender maintains cwnd. Protects the network.
  • Actual send rate = min(rwnd, cwnd).
  • Slow start: cwnd doubles per RTT. Congestion avoidance: cwnd increases by 1 MSS per RTT.
  • On loss: cwnd is halved (AIMD). On timeout: cwnd resets to 1 (full slow start).
  • BBR (Google) is bandwidth-based, not loss-based — performs better on high-latency links.
TCP flow control and buffer tuning
// Flow control: receiver advertises window in every ACK
//
// Sender                              Receiver (rwnd = 64KB)
//   │──── 1KB data ─────────────────>│  rwnd: 64→63KB in ACK
//   │──── 1KB data ─────────────────>│  rwnd: 63→62KB in ACK
//   │  ... (sends up to rwnd) ──────>│
//   │<─── ACK, rwnd=0 ───────────────│  Receiver buffer full! App slow to read
//   │  (sender blocks — zero window) │
//   │──── ZWP (Zero Window Probe) ──>│  Sender probes periodically
//   │<─── ACK, rwnd=32KB ────────────│  Receiver freed buffer space
//   │  (sender resumes) ─────────────│

// Java — increase socket receive buffer to reduce flow control stalls:
Socket socket = new Socket();
socket.setReceiveBufferSize(256 * 1024);  // 256KB receive buffer
socket.setSendBufferSize(256 * 1024);     // 256KB send buffer

// For high-throughput servers, tune OS-level TCP buffers:
// Linux: sysctl -w net.core.rmem_max=16777216
//        sysctl -w net.ipv4.tcp_rmem="4096 87380 16777216"
3

UDP — User Datagram Protocol

UDP is a connectionless, unreliable transport protocol that sacrifices guaranteed delivery for low overhead and minimal latency — ideal for DNS, video streaming, gaming, and QUIC.

  • UDP is connectionless — no handshake, no ACKs, no retransmission, no ordering guarantee.
  • UDP header is 8 bytes; TCP is 20 bytes minimum — UDP has less overhead.
  • Best for: DNS, video streaming, VoIP, gaming, NTP, DHCP.
  • QUIC (HTTP/3) is built on UDP — adds reliability and multiplexing without TCP's head-of-line blocking.
  • Each UDP datagram is independent — datagrams can arrive out of order or not at all.
  • UDP checksum is optional in IPv4 but mandatory in IPv6.
UDP header structure and Java DatagramSocket
// UDP Header (8 bytes):
// ┌─────────────────┬─────────────────┐
// │ Source Port (2B)│ Dest Port (2B)  │
// ├─────────────────┼─────────────────┤
// │ Length (2B)     │ Checksum (2B)   │
// ├─────────────────┴─────────────────┤
// │ Data (variable)                   │
// └───────────────────────────────────┘
// Total overhead: 8 bytes (vs TCP's 20B minimum)

// Java UDP server:
DatagramSocket server = new DatagramSocket(5353);
byte[] buf = new byte[512];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
server.receive(packet);                         // blocks until a datagram arrives
String msg = new String(packet.getData(), 0, packet.getLength());

// Java UDP client:
DatagramSocket client = new DatagramSocket();
byte[] data = "hello".getBytes();
InetAddress addr = InetAddress.getByName("localhost");
DatagramPacket send = new DatagramPacket(data, data.length, addr, 5353);
client.send(send);                              // fire and forget — no confirmation
4

Ports & Sockets

A port identifies a specific process on a host; a socket is the combination of IP address + port + protocol that uniquely identifies one end of a network connection.

  • Ports (0–65535) identify processes; IP addresses identify hosts.
  • Well-known ports: HTTP=80, HTTPS=443, SSH=22, DNS=53, MySQL=3306, Redis=6379.
  • Ports below 1024 require root privileges to bind on Linux/Mac.
  • A socket is the 5-tuple: (protocol, src IP, src port, dst IP, dst port).
  • Ephemeral ports (49152–65535) are OS-assigned to the client side of connections.
  • One server port can handle thousands of connections — differentiated by client IP+port.
Well-known ports and Java socket ports
// Well-known ports (0–1023):
// 20/21  — FTP (data/control)
// 22     — SSH
// 25     — SMTP
// 53     — DNS (UDP + TCP)
// 80     — HTTP
// 110    — POP3
// 143    — IMAP
// 443    — HTTPS (HTTP over TLS)
// 3306   — MySQL
// 5432   — PostgreSQL
// 6379   — Redis
// 8080   — HTTP alternate (dev servers, Spring Boot default)
// 9092   — Apache Kafka

// Java: bind server to a specific port
ServerSocket server = new ServerSocket(8080);   // privileged port: needs root if < 1024
System.out.println("Listening on port 8080");

Socket client = new Socket("api.example.com", 443);
int localPort = client.getLocalPort();          // OS assigned ephemeral port, e.g. 54231
int remotePort = client.getPort();              // 443
System.out.println("Ephemeral port: " + localPort);
5

TCP vs UDP

TCP provides reliable, ordered, connection-based delivery at the cost of overhead; UDP provides fast, connectionless, best-effort delivery. The right choice depends on whether reliability or speed is the higher priority.

  • TCP: reliable, ordered, connection-oriented, flow/congestion controlled — higher overhead.
  • UDP: unreliable, unordered, connectionless, no flow control — minimal overhead.
  • TCP header = 20 bytes min; UDP header = 8 bytes.
  • Use TCP for correctness-critical applications; UDP for latency-critical ones.
  • QUIC (HTTP/3) and WebRTC implement reliability on top of UDP for the best of both worlds.
  • DNS uses UDP for speed but falls back to TCP for large responses (> 512 bytes).
TCP vs UDP comparison table
// TCP vs UDP comparison:
// ┌──────────────────────┬─────────────────────┬──────────────────────┐
// │ Property             │ TCP                 │ UDP                  │
// ├──────────────────────┼─────────────────────┼──────────────────────┤
// │ Connection           │ Connection-oriented  │ Connectionless       │
// │ Reliability          │ Guaranteed delivery  │ Best-effort          │
// │ Ordering             │ Guaranteed           │ Not guaranteed       │
// │ Error checking       │ Yes (+ retransmit)   │ Checksum only        │
// │ Flow control         │ Yes (rwnd)           │ No                   │
// │ Congestion control   │ Yes (cwnd)           │ No                   │
// │ Header size          │ 20 bytes minimum     │ 8 bytes              │
// │ Speed                │ Slower               │ Faster               │
// │ Connection setup     │ 3-way handshake      │ None                 │
// │ State                │ Stateful             │ Stateless            │
// │ Use cases            │ HTTP, SSH, DB, SMTP  │ DNS, video, gaming   │
// └──────────────────────┴─────────────────────┴──────────────────────┘
Learn this free with Aria, your AI tutor → AiCanCode.org/learn/computer-networks