Broadcast to a Network example server client c code
If you have a network card installed in your PC and you have a correctly configured network, you should be able to test the broadcast server and client programs successfully. This section will demonstrate the broadcast server broadcasting from a host named rhel54x64, on the interface card eth0 (IP address 192.168.0.1).
Compete Application code can be found from here.
The broadcast server is told to broadcast on interface card 192.168.0.1 by performing the following:
[root@rhel54x64 socket]#./udp-broadcast-server 192.168.0.255:9097 '192.168.0.1:*' &
Notice that there are two command-line arguments given on the command line. These are
- The broadcast address and port number to which the messages are directed.
- The source address and port number, from which the broadcasts will originate.
The second address specifies the local IP address of the socket to be used for the broadcast. This, in effect, chooses the network interface card that the broadcasting will take place on (thus choosing the network for the broadcast). The asterisk that follows the colon character specifies that any local port number is to be used. This is done because the actual port number used in this case does not need to be agreed upon in advance (any port will do).
If you fail to bind the local end of the socket correctly, you will experience something like this:
[root@rhel54x64 socket]#./udp-broadcast-server 192.168.0.255:9097 &
Invalid argument: sendto()
+ Exit 1 ./stksrv 192.168.0.255:9096
The sendto(2) function fails because the server program binds a default local address of 127.0.0.1 to the socket. This cannot work because no 192.168.0.* address can be reached from the 127.*.*.* network. This is not detected until the sendto(2) function attempts to perform the broadcast.
Three possible solutions to this problem exist:
- Be certain that the local end of the socket is explicitly bound to the correct interface card, which is to be used for the broadcast (192.168.0.1 in the demonstration).
- Use a wild local socket address (INADDR_ANY). In the example program, this can be specified on the command line as '*:*'.
- Don't bind(2) the local address for the socket at all (leave out the call to bind(2) completely).
Omitting the bind(2) function call is effectively the same as binding to INADDR_ANY and specifying a port number of zero (allowing any choice of port number). The choice used depends upon the amount of control that you want to exert over the choice of the network interface card.