UDP实现组播发送端和接收端
发送端
#include<sys/socket.h>
#include<stdio.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
int main()
{
int ret;
int sfd=socket(AF_INET,SOCK_DGRAM,0);
if(sfd==-1)perror("socket error");
struct in_addr address;
inet_pton(AF_INET,"239.0.0.10",&address.s_addr);
setsockopt(sfd,IPPROTO_IP,IP_MULTICAST_IF,&address,sizeof(address));
struct sockaddr_in caddr;
caddr.sin_family=AF_INET;
caddr.sin_port=htons(8888);
inet_pton(AF_INET,"192.168.101.231",&caddr.sin_addr.s_addr);
int caddrlen=sizeof(caddr);
while(true)
{
ret=sendto(sfd,"this is send host",strlen("this is send host"),0,(struct sockaddr*)&caddr,caddrlen);
if(ret==-1)
{
perror("sendto error");
break;
}
sleep(1);
}
close(sfd);
return 0;
}
接收端
#include<sys/socket.h>
#include<stdio.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
#include<net/if.h>
int main()
{
int ret;
int rfd=socket(AF_INET,SOCK_DGRAM,0);
if(rfd==-1)perror("socket error");
struct ip_mreqn mreqn;
inet_pton(AF_INET,"192.168.101.231",&mreqn.imr_address);//本地地址
inet_pton(AF_INET,"239.0.0.10",&mreqn.imr_address);//多播地址
mreqn.imr_ifindex=if_nametoindex("ens33");//获取网卡编号
setsockopt(rfd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreqn,sizeof(mreqn));
struct sockaddr_in raddr;
raddr.sin_family=AF_INET;
raddr.sin_port=htons(8888);
inet_pton(AF_INET,"192.168.101.231",&raddr.sin_addr.s_addr);
int raddrlen=sizeof(raddr);
ret=bind(rfd,(struct sockaddr*)&raddr,raddrlen);
if(ret==-1)perror("bind error");
char buffer[1024]={'\0'};
while(true)
{
ret=recvfrom(rfd,buffer,1024,0,(struct sockaddr*)&raddr,(socklen_t*)&raddrlen);
if(ret==-1)
{
perror("recv error");
break;
}
else if(ret==0)
{
printf("连接断开\n");
break;
}
else
{
printf("收到了数据:%s\n",buffer);
}
}
close(rfd);
return 0;
}