Networking in C · beginner · ~8 min

TCP vs UDP — when to pick which

Pick the right transport protocol for the job.

Lesson

TCP (Transmission Control Protocol): bytes arrive in order, with no duplicates and no loss, but possibly with delay if a packet had to be retransmitted. The kernel handles the retransmits, ordering, and flow control for you. Used by HTTP, SSH, SMTP, Git, almost everything you interact with.

UDP (User Datagram Protocol): each sendto() becomes one packet on the wire. The packet may arrive, may not arrive, or may arrive out of order. If you want reliability, you build it on top. Used by DNS, video conferencing, gaming, QUIC.

Defaults to know:

  • TCP byte-stream: don't expect message boundaries. Two send() calls of 4 bytes might arrive as one recv() of 8.
  • UDP datagram: message boundaries preserved (one sendto = one packet at the receiver), but no delivery guarantee.

For everything in this course we use TCP unless an exercise specifically calls out UDP.

Code examples

int tcp = socket(AF_INET, SOCK_STREAM, 0);  /* TCP */
int udp = socket(AF_INET, SOCK_DGRAM,  0);  /* UDP */

Common mistakes

  • Expecting message boundaries from TCP. They aren't there. Frame your messages with length prefixes or a delimiter.

Summary

TCP = reliable, ordered byte stream (no message boundaries). UDP = best-effort datagrams (boundaries preserved, delivery not). Default to TCP.

Practice with these exercises