Saturday, September 10, 2011

udp broadcast client example in c




The general steps used by the client program are these:
  1. The socket is created (lines 68 to 70).
  2. The broadcast address is formed (lines 75 to 83).
  3. The SO_REUSEADDR option is enabled (lines 89 to 96).
  4. Bind the broadcast address to the current socket (lines 101 to 106).
  5. Begin a broadcast receiving loop (line 108).
  6. Receive a broadcast (lines 112 to 120).
  7. Write the broadcast information to the standard output (lines 122 to 125).
  8. 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

Output

[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

1 comment:

  1. I have received some email regarding using the server-client model.
    I feel readers are not taking the correct file. Let me know if I need to re post the same codes again.

    thanks,
    Saurabh Gupta
    sgupta@ccplusplus.com

    ReplyDelete