gpt4 book ai didi

c - 使用 SO_BINDTODEVICE 接口(interface)上没有流量绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-04 10:27:40 30 4
gpt4 key购买 nike

我正在尝试使用 SO_BINDTODEVICE 将我的套接字绑定(bind)到 eth0。我将 eth0 传递给变量 opt。我的套接字名称是 socketfd

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0) {
perror("socket(): error ");
return 0;
}
struct ifreq ifr;

memset(&ifr, 0, sizeof(struct ifreq));
fprintf(stderr,ifr.ifr_name, sizeof(ifr.ifr_name), opt);
ioctl(sockfd, SIOCGIFINDEX, &ifr);
setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, opt, strlen(opt));
fprintf(stderr, "The bind is done on interface %s \n", opt);
fprintf(stderr, "opt length is %zu \n", strlen(opt));

为了进行一些调试,我将 opt 和 strlen(opt) 的值重定向到日志文件,它们正确地获取了值。

cat /home/cayman/log.txt
The bind is done on interface eth0
opt length is 4

我还通过在 eth0 上捕获数据包来进行验证,但我没有看到通过 eth0 的流量。所有看到的都是其他与网络相关的流量,如下所示:

tshark -i eth0
1 0.000000 Cisco_51:fd:09 -> Spanning-tree-(for-bridges)_00 STP 62 Conf. Root = 32768/78/00:24:50:51:fd:00 Cost = 0 Port = 0x8009
2 0.326720 192.168.78.1 -> 224.0.0.13 PIMv2 70 Hello
3 1.030538 Cisco_51:fd:09 -> Cisco_51:fd:09 LOOP 62 Reply
4 2.004544 Cisco_51:fd:09 -> Spanning-tree-(for-bridges)_00 STP 62 Conf. Root = 32768/78/00:24:50:51:fd:00 Cost = 0 Port = 0x8009
5 3.254223 192.168.78.1 -> 224.0.0.10 EIGRP 76 Hello
6 4.010168 Cisco_51:fd:09 -> Spanning-tree-(for-bridges)_00 STP 62 Conf. Root = 32768/78/00:24:50:51:fd:00 Cost = 0 Port = 0x8009
7 6.014839 Cisco_51:fd:09 -> Spanning-tree-(for-bridges)_00 STP 62 Conf. Root = 32768/78/00:24:50:51:fd:00 Cost = 0 Port = 0x8009
8 7.896252 192.168.78.1 -> 224.0.0.10 EIGRP 76 Hello
9 8.023003 Cisco_51:fd:09 -> Spanning-tree-(for-bridges)_00 STP 62 Conf. Root = 32768/78/00:24:50:51:fd:00 Cost = 0 Port = 0x8009

我还查看了 this thread我确保我以 super 用户身份运行我的代码。我还看了 man page的 SO_BINDTODEVICE 但我不确定会丢失什么。有什么建议吗?

最佳答案

您没有检查大多数调用的返回码。它们中的一个或多个可能会以一种揭示额外信息的方式失败。您应该(始终)检查返回值是否有错误。

编辑:我在您的代码中添加了错误处理:

#include <sys/socket.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <string.h>

int main() {
const char* opt = "wlp4s0";
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0) {
perror("socket(): error ");
return 1;
}
struct ifreq ifr;

memset(&ifr, 0, sizeof(struct ifreq));
fprintf(stderr,ifr.ifr_name, sizeof(ifr.ifr_name), opt);
if (ioctl(sockfd, SIOCGIFINDEX, &ifr) < 0) {
perror("ioctl(): error ");
return 2;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, opt, strlen(opt)) > 0) {
perror("setsockopt(): error ");
return 3;
}
fprintf(stderr, "The bind is done on interface %s \n", opt);
fprintf(stderr, "opt length is %zu \n", strlen(opt));
}

并且发现 ioctl() 失败了。然后我注意到您没有初始化 ifr.ifr_name。如果您将 opt 复制到 ifr.ifr_name 中,您的问题会消失吗?

关于c - 使用 SO_BINDTODEVICE 接口(interface)上没有流量绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41046654/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com