Contents
7
4.
Using Internet Datagram Sockets
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .86
Preparing Address Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .88
Declaring Socket Address Variables . . . . . . . . . . . . . . . . . . . . . . . . . . .88
Getting the Remote Host's Network Address . . . . . . . . . . . . . . . . . . . .89
Getting the Port Address for the Desired Service . . . . . . . . . . . . . . . .90
Using a Wildcard Local Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91
Writing the Server and Client Processes . . . . . . . . . . . . . . . . . . . . . . . . .92
Creating Sockets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .92
Binding Socket Addresses to Datagram Sockets . . . . . . . . . . . . . . . . .93
Sending and Receiving Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95
Sending Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95
Receiving Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .96
Flag Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .98
Closing a Socket. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .100
Example Using Datagram Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101
5.
Advanced Topics for Internet Datagram Sockets
SO_BROADCAST Socket Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .111
Specifying a Default Socket Address . . . . . . . . . . . . . . . . . . . . . . . . . . .112
When to Specify a Default Socket Address . . . . . . . . . . . . . . . . . . . . .113
Synchronous I/O Multiplexing with Select. . . . . . . . . . . . . . . . . . . . . . .114
Sending and Receiving Data Asynchronously . . . . . . . . . . . . . . . . . . . .115
Sending and Receiving IP Multicast Datagrams. . . . . . . . . . . . . . . . . .116
Sending IP Multicast Datagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . .116
Receiving IP Multicast Datagrams . . . . . . . . . . . . . . . . . . . . . . . . . . .118
Nonblocking I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121