分类: C/C++
2007-06-09 16:48:23
#include #include #include #include #include #include #include #include #include #define PORT 51654 int main(int argc,char* argv[]) { int sockfd; struct sockaddr_in their_addr; struct in_addr addr; struct hostent *he; int broadcast = 1; int num = 0; if(argc != 3) { fprintf(stderr,"Usage: broadcase hostname message\n"); exit(1); } if( inet_aton(argv[1],&addr) == 0) { he = gethostbyname(argv[1]); //Domain addr.s_addr = (*(unsigned int *)*he->h_addr_list[0]); } if( (sockfd = socket(AF_INET,SOCK_DGRAM,0)) == -1 ) { perror("socket function!\n"); exit(1); } if( setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,&broadcast,sizeof(broadcast)) == -1) { perror("setsockopt function!\n"); exit(1); } their_addr.sin_family = AF_INET; their_addr.sin_port = htons(PORT); their_addr.sin_addr = addr; if( (num = sendto( sockfd,argv[2],strlen(argv[2]),0,(struct sockaddr *)&their_addr,sizeof(struct sockaddr) )) == -1) { perror("sendto function!\n"); exit(1); } printf("Send %d bytes to %s\n",num,inet_ntoa(their_addr.sin_addr) ); close(sockfd); return 0; } |