gpt4 book ai didi

c - 绑定(bind)与 SO_BINDTODEVICE 套接字

转载 作者:IT王子 更新时间:2023-10-29 00:06:24 28 4
gpt4 key购买 nike

我在 linux (ubuntu 13.10) 上运行一个项目,它使用连接到设备的原始套接字。

这是我的代码:

/* builed socket */
if ((sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1) {
perror("listener: socket");
return -1;
}

/* Set interface to promiscuous mode */
strncpy(ifopts.ifr_name, ifName, IFNAMSIZ-1);
ioctl(sockfd, SIOCGIFFLAGS, &ifopts);
ifopts.ifr_flags |= IFF_PROMISC;
ioctl(sockfd, SIOCSIFFLAGS, &ifopts);

/* Allow the socket to be reused - incase connection is closed prematurely */
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof sockopt) == -1) {
perror("setsockopt");
close(sockfd);
return -2;
}

但是我的计算机上有 2 个 NIC 卡,我只想听其中一个。让我们说民族风。我发现两个选项 bind 和 SO_BINDTODEVICE 如下:

/* option 1. Bind to device */
if (setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, ifName, IFNAMSIZ-1) == -1) {
perror("SO_BINDTODEVICE");
close(sockfd);
return -4;
}


/* option 2. Bind to device */
memset(&sock_address, 0, sizeof(sock_address));
sock_address.sll_family = PF_PACKET;
sock_address.sll_protocol = htons(ETH_P_ALL);
sock_address.sll_ifindex = if_nametoindex(ifName);
if (bind(sockfd, (struct sockaddr*) &sock_address, sizeof(sock_address)) < 0) {
perror("bind failed\n");
close(sockfd);
return -4;
}

只有绑定(bind)有效。所以我的问题是两者之间有什么区别?

最佳答案

来自 Linux 手册页 man 7 socket对于套接字选项 SO_BINDTODEVICE:

Note that this works only for some socket types, particularly AF_INET sockets. It is not supported for packet sockets (use normal bind(2) there).

关于c - 绑定(bind)与 SO_BINDTODEVICE 套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20240260/

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