How to UDP Broadcast with C in Linux? How to UDP Broadcast with C in Linux? linux linux

How to UDP Broadcast with C in Linux?


In many IP stack, such as Linux, this code does not work. Your socket must have broadcast permissions. Try this:

bcast_sock = socket(AF_INET, SOCK_DGRAM, 0);int broadcastEnable=1;int ret=setsockopt(bcast_sock, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable));/* Add other code, sockaddr, sendto() etc. */


Unwind has it right, except you should use 'sendto'

Here is an example, that assumes you already have a socket. It was taken from clamav

static voidbroadcast(const char *mess){    struct sockaddr_in s;    if(broadcastSock < 0)        return;    memset(&s, '\0', sizeof(struct sockaddr_in));    s.sin_family = AF_INET;    s.sin_port = (in_port_t)htons(tcpSocket ? tcpSocket : 3310);    s.sin_addr.s_addr = htonl(INADDR_BROADCAST);    cli_dbgmsg("broadcast %s to %d\n", mess, broadcastSock);    if(sendto(broadcastSock, mess, strlen(mess), 0, (struct sockaddr *)&s, sizeof(struct sockaddr_in)) < 0)        perror("sendto");}


Typically using the Berkeley sockets API, to sendto() one or more datagrams to a known broadcast-class IP address.