The general steps used by the client program are these:
- The socket is created (lines 68 to 70).
- The broadcast address is formed (lines 75 to 83).
- The SO_REUSEADDR option is enabled (lines 89 to 96).
- Bind the broadcast address to the current socket (lines 101 to 106).
- Begin a broadcast receiving loop (line 108).
- Receive a broadcast (lines 112 to 120).
- Write the broadcast information to the standard output (lines 122 to 125).
- Repeat step 5.
Pay special attention to step 4. To receive the broadcast, there has to be a client program that has this address bound to the socket. This identifies the client program as the intended recipient of the messages.
There is a problem with this approach, however. If one client program binds this address, then no others on the same host will be able to bind that address. This would defeat the purpose of broadcasting. Enabling SO_REUSEADDR allows multiple client programs to receive from the same broadcast address, on the same host.
To compile the demonstration client program, you can use the following command:
Take this mkaddr.c file for compiling the code
[root@rhel54x64 socket]# gcc -c -D_GNU_SOURCE -Wall -Wreturn-type -g udp-broadcast-client.c
[root@rhel54x64 socket]# gcc -c -D_GNU_SOURCE -Wall -Wreturn-type -g mkaddr.c
[root@rhel54x64 socket]# gcc -g udp-broadcast-client.o mkaddr.o -o udp-broadcast-client
Here is the complete udp broadcast client-server application