#include #include #include #include #include #include #include #include #include #define PORT 9999 /* Port number */ #define GROUP "239.0.0.1" /* Multicast address */ /** * Simple multicast server to broadcast the current time. */ int main(int argc, char *argv[]) { struct sockaddr_in sad; /* structure to hold server's address */ int addrlen; /* length of address */ int sd; /* socket descriptor */ int sleepDelay; /* time between sends in seconds */ char buf[50]; /* buffer to hold time */ u_char ttl; /* time to live option */ sleepDelay = 5; /* 5 seconds */ /* set up socket */ sd = socket(AF_INET, SOCK_DGRAM, 0); if (sd < 0) { perror("Error in socket()"); exit(1); } /* The following code snippet does not contain any multicast specifics */ memset((char *)&sad, 0, sizeof(sad)); /* Init memory to zero */ sad.sin_family = AF_INET; /* Set family to internet */ sad.sin_addr.s_addr = htonl(INADDR_ANY); /* Set the local IP address */ sad.sin_port = htons(PORT); /* Set the port number */ addrlen = sizeof(sad); /* Set the address length */ /* Set the socket options, in this case set the time to live * * IP_MULTICAST_TTL - Number of intermediate systems through which a * * multicast datagram can be forwarded. */ ttl = 2; if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) < 0) { perror("Error in setsockopt()"); exit(1); } /* Set the multicast address */ sad.sin_addr.s_addr = inet_addr(GROUP); printf("Server Init complete\n"); /* Start broadcasting the local time */ while (1) { time_t t = time(0); /* get current time */ sprintf(buf, "Current time: %-24.24s", ctime(&t)); /* make readable */ printf("Sending message: %s\n", buf); /* sendTo is used to send a message to another socket, the socket is * * not required to be in a connected state (unlike send). */ if (sendto(sd, buf, sizeof(buf), 0, (struct sockaddr *)&sad, addrlen) < 0) { perror("Error in sendto()"); exit(1); } sleep(sleepDelay); } return 0; }