Chapter 2 ■ UDp
37
The server needs to bind() to an address and port before it can receive incoming packets. Client UDP programs
can just start sending, and the operating system will choose a port number for them automatically.
Since UDP is built atop the actual behavior of network packets, it is unreliable. Packets can be dropped either
because of a glitch on a network transmission medium or because a network segment becomes too busy. Clients
have to compensate for this by being willing to retransmit a request until they receive a reply. To prevent making
a busy network even worse, clients should use exponential backoff as they encounter repeated failure, and they
should also make their initial wait time longer if they find that round-trips to the server are taking longer than they
were initially willing to wait.
Request IDs are crucial to combat the problem of reply duplication, where a reply you thought was lost arrives
later after all and could be mistaken for the reply to your current question. If randomly chosen, request IDs can also
help protect against naive spoofing attacks.
When using sockets, it is important to distinguish the act of binding—by which you grab a particular UDP port for
your own use—from the act that the client performs by connecting, which limits all replies received so that they can
come only from the particular server to which you want to talk.
Among the socket options available for UDP sockets, the most powerful is broadcast, which lets you send packets
to every host on your subnet without having to send to each host individually. This can help when programming local
LAN games or other cooperative computation, and it is one of the few reasons that you would select UDP for new
applications.