多播的测试代码如下:
#include #include #include #include #include #include #include #include #include #include int main(int argc, char*argv[]) { int sockfd; // 套接字文件描述符 struct sockaddr_in local_addr; // 本地地址 int err = -1; char group[16] = "224.0.0.88"; // 多播组 IP sockfd = socket(AF_INET, SOCK_DGRAM, 0); //建立套接字if (sockfd == -1) { perror("socket()"); return -1; } // 初始化地址 memset(&local_addr, 0, sizeof(local_addr)); local_addr.sin_family = AF_INET; local_addr.sin_addr.s_addr = htonl(INADDR_ANY); local_addr.sin_port = htons(8080); // 绑定socket err = bind(sockfd,(struct sockaddr*)&local_addr, sizeof(local_addr)); if(err < 0) { perror("bind()"); return -2; } struct ip_mreq mreq; // 多播地址结构体 // 加入多播组,相当于创建一个QQ群,某人加入此群mreq.imr_multiaddr.s_addr = inet_addr(group); // 多播地址,类似于 QQ 群号 mreq.imr_interface.s_addr = htonl(INADDR_ANY);// 将本机加入多播组,类似于某人加入此群// 加入多播组err = setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)); if (err < 0) { perror("[50]setsockopt():IP_ADD_MEMBERSHIP"); return -4; } int times = 0; int addr_len = 0; char buff[256] = {0}; int n = 0; printf("加入多播组成功,准备接收数据"); //接收数据while(1) { addr_len = sizeof(local_addr); memset(buff, 0, sizeof(buff)); // 接收数据 n = recvfrom(sockfd, buff, sizeof(buff), 0,(struct sockaddr*)&local_addr, &addr_len); if( n == -1) { perror("recvfrom()"); close(sockfd); return -1;} printf("Recv message from server: %s", buff); } // 退出广播组 err = setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP,&mreq, sizeof(mreq)); if (err < 0) { perror("[79]setsockopt():IP_DROP_MEMBERSHIP"); return -4; } close(sockfd); return 0; }
在linux编译运行时,出现如下的错误:
查询相关资料得到的答案如下:
It means that the tool is trying to use multicast but the network interface doesn't support it There are two likely causes:
·Your machine doesn't have multicast support enabled. For example, on linux and FreeBSD it is possible to compile a kernel which doesn't support multicast.
·You don't have a route for multicast traffic. Some systems don't add this by default, and you need to run:route add -net 224.0.0.0 netmask 255.255.255.255 eth0(or similar). If you wish to use RAT in unicast mode only, it is possible to add the multicast route on the loopback interface.
这主要和当前的网络配置有关,因为多播IP地址没有加入到路由表中。
解决方法:把需要用到的多播地址(如本例的224.0.0.88)加入到路由表中,命令如下:
sudo route add -net 224.0.0.88 netmask 255.255.255.255 eth0
224.0.0.88:为当前使用的多播IP地址
eth0:为当前使用的有效网卡
其它辅助命令:
sudo route del -net 224.0.0.88 netmask 255.255.255.255 eth0 //把224.0.0.88从路由表中删除
route -n //查看路由表信息
具体 *** 作过程如下图:
需要C/C++ linux服务器架构师学习资料私信“资料”(资料包括C/C++,linux,golang技术,Nginx,ZeroMQ,MysqL,Redis,fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,TCP/IP,协程,DPDK,ffmpeg等),免费分享
总结以上是内存溢出为你收集整理的linux 路由表_Linux多播问题(No such device)解决方法全部内容,希望文章能够帮你解决linux 路由表_Linux多播问题(No such device)解决方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)