您的位置:首页 > 文旅 > 旅游 > UDP实现组播发送端和接收端

UDP实现组播发送端和接收端

2024/12/23 8:31:11 来源:https://blog.csdn.net/weixin_74027669/article/details/142345439  浏览:    关键词: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;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com