Skip to content

Instantly share code, notes, and snippets.

@pmichna
Last active December 18, 2015 10:39
Show Gist options
  • Save pmichna/5769966 to your computer and use it in GitHub Desktop.
Save pmichna/5769966 to your computer and use it in GitHub Desktop.
How to do broadcast with UDP in UNIX.
struct sockaddr_in s;
int fd_socket = socket(PF_INET, SOCK_DGRAM, 0);
int bcastEnable = 1;
int32_t data = 1;
if (fd_socket < 0)
perror("socket");
if(setsockopt(fd_socket, SOL_SOCKET, SO_BROADCAST, &bcastEnable, sizeof(bcastEnable)))
perror("setsockopt");
memset(&s, 0, sizeof(struct sockaddr_in));
s.sin_family = AF_INET;
s.sin_port = htons(2987); // or some other port
s.sin_addr.s_addr = htonl(INADDR_BROADCAST);
/* sending broadcast to other hosts in the network */
if(sendto(fd_socket, &data, sizeof(int32_t), 0, (const struct sockaddr *)&s, sizeof(struct sockaddr_in)) < 0)
ERR("sendto");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment