Sockets & Network Programming

a UDP socket

If a TCP socket is a phone call, a UDP socket is dropping postcards in a mailbox. You write an address on each postcard and send it; it usually arrives, but it might be lost, might arrive out of order, and there is no ring, no handshake, and no hang-up. A UDP socket is an endpoint that sends and receives independent, self-contained packets called datagrams, with no connection and no delivery guarantees.

You create one as a datagram socket (socket(AF_INET, SOCK_DGRAM, 0)). Because there is no connection, you do not connect and then send; instead each call says where to go: sendto(fd, data, address) sends one datagram to that address, and recvfrom(fd, buffer) receives one datagram and tells you who it came from. A key property: UDP preserves message boundaries. One sendto becomes exactly one recvfrom — if you send a 200-byte datagram, the other side reads it as a single 200-byte unit, never half of it or two glued together. The kernel adds only ports and a checksum; it does not retransmit, reorder, or pace anything.

Why it matters: UDP is not broken or inferior — it is a deliberate choice for applications that prefer timeliness and simplicity over guaranteed in-order delivery. DNS lookups, online games, voice and video calls (VoIP), and newer transports like QUIC all use UDP, because a late retransmission of an old voice sample or game position is worse than just moving on. The trade-off is that if your app needs reliability or ordering, you must build it yourself on top of UDP — which is exactly what QUIC does, in user space.

A DNS client sends one small query datagram with sendto() to the resolver at port 53, then waits in recvfrom() for one reply datagram. No handshake, no teardown — request and answer are each a single packet, which is why DNS is fast and lightweight.

One sendto, one recvfrom: UDP keeps message boundaries intact.

UDP gives no reliability, ordering, or congestion control. If a datagram is lost, it is simply gone — nothing retransmits it. An app that needs those guarantees must add them itself, or use TCP instead.

Also called
datagram socketSOCK_DGRAMUDP 套接字資料報通訊端