发送端代码,基本步骤:
1,创建一个udpsocket
sock = socket(PF_INET, SOCK_DGRAM, 0);
2,绑定到一个发送数据的网卡,或者绑定到ADDR_ANY,
saddr.sin_family = AF_INET;
saddr.sin_port = htons(0); // 发送端任意使用个端口,因为要调用bind,所以用0,让系统随便算个可用的
saddr.sin_addr.s_addr = htonl(INADDR_ANY); // 绑定到任意地址,如果要在某个物理网卡上组播,设置那个地址。这个地址设置和路由有关,如果设置ANADDR_ANY,但是路由表中localhost的组播地址优先的话,可能导致不走局域网网卡来组播。
int status = bind(sock, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in));//绑定
3,连接到组播地址,或者在发送的时候用sendto指定。
4,设置ttl
// Set multicast packet TTL to 3; default TTL is 1
setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl,
sizeof(unsigned char));
5,设置回环组播,这样自己可以在本机localhost上测试
// send multicast traffic to myself too
status = setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP,
&one, sizeof(unsigned char));
6,发送数据,和普通的udp数据发送是一样的
// set destination multicast address
saddr.sin_family = PF_INET;
saddr.sin_addr.s_addr = inet_addr("226.0.0.1");
saddr.sin_port = htons(4096);
// put some data in buffer
strcpy(buffer, "Hello world\n");
socklen = sizeof(struct sockaddr_in);
// receive packet from socket
status = sendto(sock, buffer, strlen(buffer), 0,
(struct sockaddr *)&saddr, socklen);
接收端代码,基本步骤:
1,创建一个udpsocket
// open a UDP socket
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
2,绑定到一个希望用于接收的网卡,或者绑定到ADDR_ANY
saddr.sin_family = PF_INET;
saddr.sin_port = htons(4096); // listen on port 4096
saddr.sin_addr.s_addr = htonl(INADDR_ANY); // 解释参考上面
status = bind(sock, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in));
3,加入组播组
imreq.imr_multiaddr.s_addr = inet_addr("226.0.0.1");
imreq.imr_interface.s_addr = INADDR_ANY; // use DEFAULT (route configuration?) interface, e.g. "127.0.0.1" for loop test, "192.168.0.100" for LAN test.
// JOIN multicast group on default interface
status = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(const void *)&imreq, sizeof(struct ip_mreq));
4,开始接受数据
// receive packet from socket
status = recvfrom(sock, buffer, MAXBUFSIZE, 0,
(struct sockaddr *)&saddr, &socklen);