Linux多播问题(No such device)解决方法

多播的测试代码如下:
#include #include #include #include #include #include #include #include #include #includeint main(int argc, char*argv[]){int sockfd; // 套接字文件描述符struct sockaddr_in local_addr; // 本地地址int err = -1;char group[16] = "224.0.0.88"; // 多播组 IPsockfd = socket(AF_INET, SOCK_DGRAM, 0);//建立套接字 if (sockfd == -1){perror("socket()");return -1;}// 初始化地址memset(local_addr.sin_family = AF_INET;local_addr.sin_addr.s_addr = htonl(INADDR_ANY);local_addr.sin_port = htons(8080);// 绑定socketerr = bind(sockfd,(struct sockaddr*)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,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("加入多播组成功 , 准备接收数据\n");//接收数据 while(1){addr_len = sizeof(local_addr);memset(buff, 0, sizeof(buff));// 接收数据n = recvfrom(sockfd, buff, sizeof(buff), 0,(struct sockaddr*)if( n == -1){perror("recvfrom()");close(sockfd);return -1;}printf("Recv message from server: %s\n", buff);}// 退出广播组err = setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP,if (err < 0){perror("[79]setsockopt():IP_DROP_MEMBERSHIP");return -4;}close(sockfd);return 0;}在linux编译运行时 , 出现如下的错误:
Linux多播问题(No such device)解决方法文章插图
查询相关资料得到的答案如下:
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.
【Linux多播问题(No such device)解决方法】这主要和当前的网络配置有关 , 因为多播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 //查看路由表信息
具体操作过程如下图:
Linux多播问题(No such device)解决方法文章插图
需要C/C++ Linux服务器架构师学习资料私信“资料”(资料包括C/C++ , Linux , golang技术 , Nginx , ZeroMQ , MySQL , Redis , fastdfs , MongoDB , ZK , 流媒体 , CDN , P2P , K8S , Docker , TCP/IP , 协程 , DPDK , ffmpeg等) , 免费分享
Linux多播问题(No such device)解决方法文章插图