The socket API for UDP sockets is only very slightly different than what we've already learned for TCP. In fact, they are similar enough that we can take the TCP client from the last chapter and turn it into a fully functional UDP client by changing only one line of code:
- Take tcp_client.c from Chapter 3, An In-Depth Overview of TCP Connections, and find the following line of code:
hints.ai_socktype = SOCK_STREAM;
- Change the preceding code to the following:
hints.ai_socktype = SOCK_DGRAM;
This modification is included in this chapter's code as udp_client.c.
You can recompile the program using the same commands as before, and you'll get a fully functional UDP client.
Unfortunately, changing the TCP servers of the previous chapters to UDP won't be as easy. TCP and UDP server code are different enough that a slightly different approach...