• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <sys/types.h>
2 #include <sys/socket.h>
3 #include <netinet/in.h>
4 #include <errno.h>
5 #include <unistd.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <fcntl.h>
10 #include <netdb.h>
11 
12 #define	MAXBUFSIZ	8096
13 
14 static char buf[MAXBUFSIZ];
15 
main(int argc,char * argv[])16 int main(int argc, char *argv[])
17 {
18 	struct ip_mreq imr;
19 	struct sockaddr_in from_in, mcast_in;
20 	int s = 0, n = 0, one = 1;
21 	/*DHH 052697 Added for 64BIT Compatibility */
22 /*	6/2/97	Mario Gallegos changed from ifdef to ifndef (PORTING)	*/
23 #ifndef __64BIT__
24 	unsigned int len = 0;
25 #else
26 	unsigned long len = 0;
27 #endif
28 	unsigned i1, i2, i3, i4, g1, g2, g3, g4;
29 	struct hostent *hp, *gethostbyname();
30 
31 	/*int loop=0; */
32 
33 	if (argc < 4) {
34 		fprintf(stderr,
35 			"usage: %s g.g.g.g interface_name (or i.i.i.i) port\n",
36 			argv[0]);
37 		exit(1);
38 	}
39 
40 	/* set up multicast membership structure */
41 	if ((n = sscanf(argv[1], "%u.%u.%u.%u", &g1, &g2, &g3, &g4)) != 4) {
42 		fprintf(stderr, "bad group address\n");
43 		exit(1);
44 	}
45 	imr.imr_multiaddr.s_addr =
46 	    htonl((g1 << 24) | (g2 << 16) | (g3 << 8) | g4);
47 
48 	if ((hp = gethostbyname(argv[2])))
49 		memcpy(&imr.imr_interface.s_addr, hp->h_addr, hp->h_length);
50 	else if ((n = sscanf(argv[2], "%u.%u.%u.%u", &i1, &i2, &i3, &i4)) != 4) {
51 		fprintf(stderr, "Bad group interface address\n");
52 		exit(1);
53 	} else
54 		imr.imr_interface.s_addr =
55 		    htonl((i1 << 24) | (i2 << 16) | (i3 << 8) | i4);
56 
57 	/* set up socket structure */
58 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
59 		perror("can not open socket");
60 		exit(1);
61 	}
62 
63 	memset(&mcast_in, 0x00, sizeof(mcast_in));
64 	mcast_in.sin_family = AF_INET;
65 	mcast_in.sin_port = htons(atoi(argv[3]));
66 
67 	/* allow address reuse for binding multiple multicast applications to
68 	   the same group */
69 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0) {
70 		perror("setsockopt SO_REUSEADDR failed");
71 		exit(1);
72 	}
73 
74 	if (bind(s, (struct sockaddr *)&mcast_in, sizeof(mcast_in)) < 0) {
75 		perror("bind");
76 		exit(1);
77 	}
78 
79 	/* Add interface to multicast group */
80 	if (setsockopt
81 	    (s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr,
82 	     sizeof(struct ip_mreq)) < 0) {
83 		perror("can not join group");
84 		exit(1);
85 	}
86 	printf("Joined group\n");
87 
88 	/* Receive datagrams */
89 	len = sizeof(from_in);
90 	for (;;) {
91 		memset(&from_in, 0x00, sizeof(from_in));
92 		if ((n =
93 		     recvfrom(s, buf, sizeof(buf), 0,
94 			      (struct sockaddr *)&from_in, &len)) < 0) {
95 			perror("recvfrom");
96 			exit(1);
97 		}
98 		if (strcmp(buf, "quit") == 0)
99 			break;
100 		printf("%s\n", buf);
101 	}
102 	close(s);
103 	exit(0);
104 }
105