/* dgmcsend.c */ /* Demonstates the use of multicast send for datagram transfer */ #include #include #include #include #include char buf[100]; struct hostent *hp; struct hostent *gethostbyname(); struct sockaddr_in name; struct sockaddr_in sname; int namelen; struct ip_mreq mreq; /* unsigned char mgroup[4] = {0xe0, 0x00, 0x00, 0xe0}; */ unsigned char mgroup[4] = {0xe0, 0x02, 0x7f, 0xfe}; int on=1; main(argc, argv) int argc; char *argv[]; { int i; unsigned char c; int sock; int netaddr; int status; /* Create datagram socket */ sock = socket(PF_INET, SOCK_DGRAM, 0); if (sock < 0) { printf("Socket create failed \n"); exit(1); } /* Get host network address from command line parm */ hp = gethostbyname(argv[1]); if (hp == 0) { printf("Host %s not found\n", argv[1]); exit(1); } bcopy((char *)hp->h_addr, &mreq.imr_interface, 4); bcopy((char *)mgroup, &mreq.imr_multiaddr, 4); status = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)); if (status < 0) printf("Set reuse failed with %d \n", status); status = setsockopt(sock, 0 , IP_ADD_MEMBERSHIP, (char *)&mreq, sizeof(mreq)); if (status < 0) printf("Set sockopt failed with %d \n", status); printf("Join multicast status is %d \n", status); /* Fill in protocol family and port # from command line then */ /* bind the socket to the specified address. */ name.sin_family = AF_INET; name.sin_port = htons(atoi(argv[2])); bcopy((char *)mgroup, (char *)&name.sin_addr, 4); status = bind(sock, (struct sockaddr *)&name, sizeof(name)); printf("Bind status = %d \n", status); if (status < 0) exit(1); printf("Dest net address = "); for (i = 0; i < hp->h_length; i++) { c = *((char *)&name.sin_addr + i); printf(" %2x", c); } status = sendto(sock, "This is a multicast\n", 20, 0, &name, sizeof(name)); printf("%d bytes sent \n", status); exit(1); /* Wait for someone to send me a datagram.. I should receive my own */ namelen = sizeof(struct sockaddr_in); status = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *)&sname, &namelen); printf("status = %d \n", status); printf("Msg = %s \n", buf); printf("Sender net address = "); for (i = 0; i < hp->h_length; i++) { c = *((char *)&sname.sin_addr + i); printf(" %2x", c); } printf("\n"); printf("Sender port address = %x \n", sname.sin_port); }