/* ** udp_broadcaster.c -- a UDP sender that broadcasts ** this one can broadcast */ #include #include #include #include #include #include #include #include #include #include #define SERVERPORT 4950 // the port to send to int main(int argc, char *argv[]) { int sockfd; struct sockaddr_in their_addr; // connector's address information struct hostent *he; int numbytes; int broadcast = 1; //char broadcast = '1'; // if that doesn't work, try this if (argc != 3) { fprintf(stderr,"usage: udp_broadcaster hostname message\n"); exit(1); } // find the ip address for the server from its dns name if ((he=gethostbyname(argv[1])) == NULL) { // get the host info herror("gethostbyname"); exit(1); } // create the socket if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("socket"); exit(1); } // this allows sending packets to the broadcast address if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof broadcast) == -1) { perror("setsockopt (SO_BROADCAST)"); exit(1); } // fill in info about the server (address to send the packet to) their_addr.sin_family = AF_INET; // host byte order their_addr.sin_port = htons(SERVERPORT); // short, network byte order their_addr.sin_addr = *((struct in_addr *)he->h_addr); memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero); // send the string contained in argv[2] ... can send the contents // of a buffer instead if ((numbytes=sendto(sockfd, argv[2], strlen(argv[2]), 0, (struct sockaddr *)&their_addr, sizeof their_addr)) == -1) { perror("sendto"); exit(1); } printf("sent %d bytes to %s\n", numbytes, inet_ntoa(their_addr.sin_addr)); close(sockfd); return 0; }