#include #include #include #include #include /* CpSc 824 -- SIMPLE datagram multicast example... This program multicasts a outMessageBuf to multicast address: 229.8.2.4 and port 5824 (both arbitrarily chosen) and waits for replies from whatever machines receive it... */ /* The "available" multicast addresses are 225.0.0.0 through 238.255.255.255. */ #define MULTICASTADDR "229.8.2.4" #define PORTNUMBER 5824 main (argc, argv) int argc; char *argv[]; { int socketDesc; /* Socket Descriptor */ int addrLength; struct sockaddr_in destinationAddr, myAddr, responseAddr; struct hostent *hostNameBufPtr; char outMessageBuf[128]; char inMessageBuf[128]; struct timeval timeOut; fd_set readReadySet; int msgCount; char limitLanFlag = 0x1; /* Create socket from which to send */ if ((socketDesc = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("open error on socket"); exit(1); } /* BIND the socket on our end to any available port (i.e. leave it up to the system to assign a port (used for replys */ myAddr.sin_family = AF_INET; myAddr.sin_addr.s_addr = htonl(INADDR_ANY); myAddr.sin_port = htons(0); /* The zero says bind to any port */ if (bind(socketDesc, (struct sockaddr *) &myAddr, sizeof(myAddr)) < 0) { perror("bind error"); exit(1); } /* And build MULTICAST address */ destinationAddr.sin_family = AF_INET; destinationAddr.sin_addr.s_addr = htonl(inet_addr(MULTICASTADDR)); destinationAddr.sin_port = htons(PORTNUMBER); /* Set the socket to permit multicasts on the local LAN */ if (setsockopt(socketDesc, IPPROTO_IP, IP_MULTICAST_TTL, &limitLanFlag, sizeof(limitLanFlag)) != 0) { perror("setsockopt error"); exit(1); } /* Broadcast message */ strcpy(outMessageBuf, "Hello world"); if (sendto(socketDesc, outMessageBuf, strlen(outMessageBuf)+1, 0, (struct sockaddr *)&destinationAddr, sizeof(destinationAddr)) < 0) { perror("socket send error"); exit(1); } /* And wait for up to 5 seconds for replys to come back */ /* Set timeOut value for receive to 5 seconds */ timeOut.tv_sec = 5L; timeOut.tv_usec = 0L; /* Read responses from hosts accepting the multicast until a read finally times-out. */ FD_ZERO(&readReadySet); FD_SET(socketDesc,&readReadySet); msgCount = 0; while (select(socketDesc+1,&readReadySet, NULL, NULL, &timeOut) > 0) { addrLength= sizeof(responseAddr); if (recvfrom(socketDesc,inMessageBuf,sizeof(inMessageBuf),0, &responseAddr, &addrLength) < 0) { perror("socket read error"); exit(1); } /* Convert the address of the responding machine to its symbolic format */ if ((hostNameBufPtr=gethostbyaddr(&responseAddr.sin_addr.s_addr, sizeof(responseAddr.sin_addr.s_addr), AF_INET)) == NULL) { perror("gethostbyaddr error"); } else { printf("Message received from %s\n", hostNameBufPtr->h_name); } printf("Received Message=%s\n\n",inMessageBuf); msgCount++; FD_SET(socketDesc,&readReadySet); } printf("Received %d messages\n",msgCount); }