多播数据同时传递到加入特定组的大量主机
多播地址D类地址:224.0.0.0~239.255.255.255
数据的发送者和接收者
发送者:只要往多播组地址发送数据
接收者:需要加入到多播组
通过如下代码加入多播组:
/*
struct ip_mreq
{
/* 多播组地址 */
struct in_addr imr_multiaddr;
/* 加入多播组的主机地址 */
struct in_addr imr_interface;
};
*/
struct ip_mreq join_addr;
join_addr.imr_multiaddr.s_addr = inet_addr("224.1.2.3");
join_addr.imr_interface.s_addr = htonl(INADDR_ANY);//inet_addr("192.168.1.xxx");
setsockopt(sockfd,IPPROTO_IP,IP_ADD_MEMBERSHIP,(void*)&join_addr,sizeof(join_addr));
struct sockaddr_in addr;
addr.sin_port = htons(8888);
addr.sin_addr.s_addr = inet_addr("224.1.2.3");
bind(sockfd,(struct sockaddr*)&addr,sizeof(addr));
---------------------在开发板上运行如下命令以支持多播-----------------------------
route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0
代码
发送端
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<sys/select.h>
int main(int argc,char **argv)
{
if(argc < 3)
{
printf("Usage:%s <multiAddr> <port>\n",argv[0]);
return -1;
}
//1.创建socket
int sockfd = socket(AF_INET,SOCK_DGRAM,0);
if(sockfd < 0)
{
perror("socket");
return -1;
}
//设置使能发送广播数据报
int i = 1;
setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,(void*)&i,sizeof(int));
//2.准备通信地址
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(atoi(argv[2]));
serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
//4.通信
while(1)
{
char *str = "hello udp server";
int r = sendto(sockfd,str,strlen(str),0,(struct sockaddr*)&serverAddr,sizeof(serverAddr));
// printf("r = %d\n",r);
sleep(1);
}
//5.关闭
close(sockfd);
printf("Hello World!\n");
return 0;
}
接收端
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<sys/select.h>
int main(int argc,char **argv)
{
if(argc < 3)
{
printf("Usage:%s <multiaddr> <Port>\n",argv[0]);
return -1;
}
//1.创建socket
int sockfd = socket(AF_INET,SOCK_DGRAM,0);
if(sockfd < 0)
{
perror("socket");
return -1;
}
struct ip_mreq join_addr;
join_addr.imr_multiaddr.s_addr = inet_addr(argv[1]);
join_addr.imr_interface.s_addr = htonl(INADDR_ANY);
setsockopt(sockfd,IPPROTO_IP,IP_ADD_MEMBERSHIP,(void*)&join_addr,sizeof(join_addr));
//2.准备通信地址
struct sockaddr_in serverAddr;
memset(&serverAddr,0,sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(atoi(argv[2]));
// serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
//3.绑定
int res = bind(sockfd,(struct sockaddr*)&serverAddr,sizeof(serverAddr));
if(res < 0)
{
perror("bind");
return -1;
}
printf("绑定成功~~\n");
//4.通信
while(1)
{
char buf[1024] = {0};
recvfrom(sockfd,buf,sizeof(buf),0,NULL,NULL);
printf("recv data:%s\n",buf);
}
//5.关闭
close(sockfd);
printf("Hello World!\n");
return 0;
}