Linux Socket Programming by Example - Warren Gay

< BACKCONTINUE >
159231153036212041242100244042145096184016146223183074028121223008110134183016160035022023170

Setting the SO_BROADCAST Option

The topic of broadcasting with UDP has not been covered yet. However, it should be easily appreciated that the use of a broadcasting capability could be misused and cause grief on the affected networks. To avoid broadcasting when broadcasting wasn't intended, the socket is creating with the broadcasting feature disabled. If broadcasting is truly intended, then the C programmer is expected to take the trouble to enable this feature for the socket first.

The topic of broadcasting will be covered in Chapter 13, "Broadcasting with UDP." Consequently, only the option itself will be described here. The SO_BROADCAST option is a Boolean flag option, which is defined, fetched, and set with the int data type. The following example shows how to enable the SO_BROADCAST option:

					
#define TRUE    1
#define FALSE   0

int z;  /* Status code */
int s;     /* Socket s */
int so_broadcast;


so_broadcast = TRUE;

z = setsockopt(s,
    SOL_SOCKET,
    SO_BROADCAST,
    &so_broadcast,
    sizeof so_broadcast);

if ( z )
    perror("setsockopt(2)");

				

If the setsockopt(2) function returns zero, the socket s has been enabled to perform broadcasting. Note, however, that the socket type chosen must be one that is capable of broadcasting, such as a UDP socket.

< BACKCONTINUE >

Index terms contained in this section

broadcasting
     SO_BROADCAST socket option
            code example
            setting 2nd
setting
     socket options
            SO_BROADCAST 2nd
SO_BROADCAST socket option
      code example
      setting 2nd
sockets
     options
            SO_BROADCAST 2nd