Networking in C · beginner · ~8 min
Pick the right transport protocol for the job.
When you write networked C, you choose one of two transport protocols. Each handles delivery very differently.
TCP gives you a reliable, ordered stream of bytes:
The kernel does the hard work for you. It handles retransmits (resending lost data), ordering, and flow control (matching the sender's speed to what the receiver can handle).
TCP powers almost everything you use directly: HTTP, SSH, SMTP, and Git.
UDP is simpler and does far less for you. Each sendto() call becomes exactly one packet on the wire. That packet:
If you need reliability, you must build it yourself on top of UDP.
UDP is used by DNS, video conferencing, online gaming, and QUIC.
A message boundary marks where one message ends and the next begins. TCP and UDP treat these very differently.
send() calls of 4 bytes each might arrive as a single recv() of 8 bytes.sendto() arrives as one packet at the receiver. But delivery is not guaranteed.For everything in this course, use TCP unless an exercise specifically calls for UDP.
int tcp = socket(AF_INET, SOCK_STREAM, 0); /* TCP */
int udp = socket(AF_INET, SOCK_DGRAM, 0); /* UDP */
recv() may return part of a message, a whole message, or several messages joined together. Frame your messages yourself, using a length prefix or a delimiter.