broadcaster.cpp

Go to the documentation of this file.
00001 /*
00002 ** broadcaster.c -- a datagram "client" like talker.c, except
00003 **                  this one can broadcast
00004 *
00005 * From: http://beej.us/guide/bgnet/output/html/multipage/advanced.html
00006 */
00007 
00008 #include <stdio.h>
00009 #include <stdlib.h>
00010 #include <unistd.h>
00011 #include <errno.h>
00012 #include <string.h>
00013 #include <sys/types.h>
00014 #include <sys/socket.h>
00015 #include <netinet/in.h>
00016 #include <arpa/inet.h>
00017 #include <netdb.h>
00018 
00019 #define SERVERPORT 4950    // the port users will be connecting to
00020 
00021 int main(int argc, char *argv[])
00022 {
00023     int sockfd;
00024     struct sockaddr_in their_addr; // connector's address information
00025     struct hostent *he;
00026     int numbytes;
00027     int broadcast = 1;
00028     //char broadcast = '1'; // if that doesn't work, try this
00029 
00030     if (argc != 3) {
00031         fprintf(stderr,"usage: broadcaster hostname message\n");
00032         exit(1);
00033     }
00034 
00035     if ((he=gethostbyname(argv[1])) == NULL) {  // get the host info
00036         perror("gethostbyname");
00037         exit(1);
00038     }
00039 
00040     if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
00041         perror("socket");
00042         exit(1);
00043     }
00044 
00045     // this call is what allows broadcast packets to be sent:
00046     if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast,
00047         sizeof broadcast) == -1) {
00048         perror("setsockopt (SO_BROADCAST)");
00049         exit(1);
00050     }
00051 
00052     their_addr.sin_family = AF_INET;     // host byte order
00053     their_addr.sin_port = htons(SERVERPORT); // short, network byte order
00054     their_addr.sin_addr = *((struct in_addr *)he->h_addr);
00055     memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);
00056 
00057     if ((numbytes=sendto(sockfd, argv[2], strlen(argv[2]), 0,
00058              (struct sockaddr *)&their_addr, sizeof their_addr)) == -1) {
00059         perror("sendto");
00060         exit(1);
00061     }
00062 
00063     printf("sent %d bytes to %s\n", numbytes,
00064         inet_ntoa(their_addr.sin_addr));
00065 
00066     close(sockfd);
00067 
00068     return 0;
00069 }