组播报错 setsockopt:no such device

route add -net 224.0.0.0 netmask 224.0.0.0 eth0 // (‘eth0’根据网卡名字变化,如eth0、ens33)

运行报错:sendto: No such device or address,帮我分析代码有没有问题,代码如下:#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <linux/if_ether.h> #include <linux/if_packet.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if.h> #include <net/ethernet.h> #define ETH_IF_NAME "eth0" // 使用的网络接口名称 #define TEST_PACKET_SIZE 64 // 测试包大小 #define TEST_PAYLOAD "PHY Loopback Test" int create_raw_socket(const char *ifname) { int sockfd; struct ifreq ifr; // 创建原始套接字 if ((sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0) { perror("socket"); return -1; } // 获取网络接口索引 memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1); if (ioctl(sockfd, SIOCGIFINDEX, &ifr) < 0) { perror("ioctl SIOCGIFINDEX"); close(sockfd); return -1; } // 绑定套接字到网络接口 struct sockaddr_ll sll; memset(&sll, 0, sizeof(sll)); sll.sll_family = AF_PACKET; sll.sll_ifindex = ifr.ifr_ifindex; sll.sll_protocol = htons(ETH_P_ALL); if (bind(sockfd, (struct sockaddr *)&sll, sizeof(sll)) < 0) { perror("bind"); close(sockfd); return -1; } return sockfd; } int send_test_packet(int sockfd, const char *ifname) { char buffer[TEST_PACKET_SIZE]; struct ether_header *eth_hdr = (struct ether_header *)buffer; struct sockaddr_ll sll; struct ifreq ifr; // 获取网络接口的MAC地址 memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1); if (ioctl(sockfd, SIOCGIFHWADDR, &ifr) < 0) { perror("ioctl SIOCGIFHWADDR"); return -1; } // 构建以太网帧 memset(buffer, 0, TEST_PACKET_SIZE); memcpy(eth_hdr->ether_dhost, ifr.ifr_hwaddr.sa_data, ETH_ALEN); // 目标MAC地址(回环) memcpy(eth_hdr->ether_shost, ifr.ifr_hwaddr.sa_data, ETH_ALEN); // 源MAC地址 eth_hdr->ether_type = htons(ETH_P_IP); // 以太网类型(IP) // 填充测试数据 memcpy(buffer + sizeof(struct ether
03-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值