sockets · high

Sockets: TCP vs UDP

TCP and UDP are the two main transport protocols over IP. TCP (SOCK_STREAM) is a reliable, ordered, connection-oriented byte stream: it guarantees delivery and ordering through acknowledgements and retransmission and adds flow and congestion control, at the cost of higher overhead (a 20+ byte header, connection setup/teardown). UDP (SOCK_DGRAM) is connectionless and best-effort — datagrams may be lost, duplicated, or reordered with no built-in retransmission — but has minimal overhead (8-byte header) and the lowest latency. The most important practical distinction is message framing: TCP is a boundary-less byte stream, so a single send() may arrive split across several recv()s or coalesced with later data, forcing the application to frame messages itself (length prefix or delimiter), whereas UDP preserves boundaries so each recvfrom() returns exactly one datagram. Use TCP when correctness and ordering matter (HTTP, databases, file transfer, RPC) and UDP when low latency outweighs reliability or you implement your own (live audio/video, gaming, DNS, metrics, and HFT market-data feeds); UDP additionally supports broadcast and multicast one-to-many delivery that TCP cannot, and modern protocols like QUIC build reliability on top of UDP to get both control and speed.

🔑 Key line

TCP (SOCK_STREAM) is a reliable, ordered, connection-oriented byte stream with NO message boundaries (frame yourself); UDP (SOCK_DGRAM) is best-effort, connectionless, preserves datagram boundaries, and supports multicast — use TCP for correctness, UDP for low latency/multicast.

The code

// TCP — SOCK_STREAM: reliable, ordered, connection-oriented byte stream
int t = socket(AF_INET, SOCK_STREAM, 0);
// UDP — SOCK_DGRAM: unreliable, unordered, connectionless datagrams
int u = socket(AF_INET, SOCK_DGRAM, 0);
// TCP: connect()/accept(), send()/recv() a STREAM (no message bounds)
// UDP: sendto()/recvfrom() DATAGRAMS (each recv = one whole message)

What this lesson walks through

  1. 01Two transport models
  2. 02Stream vs message boundaries
  3. 03Gotcha — UDP guarantees nothing; TCP has no messages
  4. 04When to use which

TCP (SOCK_STREAM) is a reliable, ordered, connection-oriented byte stream: it guarantees delivery and order via acknowledgements and retransmission, and adds flow control and congestion control. UDP (SOCK_DGRAM) is connectionless and best-effort: datagrams may be lost, duplicated, or reordered, with no built-in retransmission — but far lower overhead and latency.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of Sockets: TCP vs UDP and 100+ animated C++ interview lessons.

← Previous
OS: POSIX Sockets — TCP Server/Client, epoll, UDP, TCP_NODELAY, TIME_WAIT
Next →
Sockets: The TCP Server/Client API Flow