2

我正在开发一个具有 LAN 和 WIFI 接口的基于 linux 的系统。但我必须只将我的套接字与 wifi 接口绑定。有什么通用的方法可以找出哪个接口是wifi,所以我可以用它来装我的插座吗?如果没有,我是否可以绑定并接收来自两个接口的请求?

目前,我正在使用 INADDR_ANY 进行绑定。我知道如何与 eth0 等特定接口绑定,但我找不到任何方法来确定 eth0 是否是 wifi 接口;至少在 C 中。使用 INADDR_ANY 我将接收发送到任何接口的数据包,但我的发送可能会尝试通过 LAN 接口发送它;这不是我想要的。

4

1 回答 1

2

这个片段可以帮助你,它比我想象的更复杂:

if (getifaddrs(&ifaddrs) < 0) {
my_loge(CRIT, "address detection failed");
return(0);
}

// zero
count = 0;

// unset all but CAP_HOST and CAP_ROUTER
sysinfo->cap &= (CAP_HOST|CAP_ROUTER);
sysinfo->cap_active &= (CAP_HOST|CAP_ROUTER);
// reset counter
sysinfo->physif_count = 0;

// mark all interfaces
TAILQ_FOREACH(netif, netifs, entries) {
netif->type = NETIF_OLD;
}

for (ifaddr = ifaddrs; ifaddr != NULL; ifaddr = ifaddr->ifa_next) {

// skip interfaces without addresses
if (ifaddr->ifa_addr == NULL) {
    my_log(INFO, "skipping interface %s", ifaddr->ifa_name);
    continue;
}

// only handle datalink addresses
if (ifaddr->ifa_addr->sa_family != NETIF_AF)
    continue;

// prepare ifr struct
memset(&ifr, 0, sizeof(ifr));
strlcpy(ifr.ifr_name, ifaddr->ifa_name, sizeof(ifr.ifr_name));


// skip non-ethernet interfaces
memcpy(&saddrll, ifaddr->ifa_addr, sizeof(saddrll));
if (saddrll.sll_hatype != ARPHRD_ETHER) {
    my_log(INFO, "skipping interface %s", ifaddr->ifa_name);
    continue;
}
index = saddrll.sll_ifindex;
memcpy(&saddrdl, ifaddr->ifa_addr, sizeof(saddrdl));
if ((saddrdl.sdl_type != IFT_BRIDGE) &&
    (saddrdl.sdl_type != IFT_ETHER)) {
if (saddrdl.sdl_type != IFT_ETHER) {
    my_log(INFO, "skipping interface %s", ifaddr->ifa_name);
    continue;
}
index = saddrdl.sdl_index;

// check for interfaces that are down
enabled = 0;
if (ioctl(sockfd, SIOCGIFFLAGS, (caddr_t)&ifr) >= 0)
    enabled = (ifr.ifr_flags & IFF_UP);

// detect interface type
type = netif_type(sockfd, index, ifaddr, &ifr);

if (type == NETIF_REGULAR) { 
    my_log(INFO, "found ethernet interface %s", ifaddr->ifa_name);
    sysinfo->physif_count++;
} else if (type == NETIF_WIRELESS) {
    my_log(INFO, "found wireless interface %s", ifaddr->ifa_name);
    sysinfo->cap |= CAP_WLAN;
    sysinfo->cap_active |= (enabled == 1) ? CAP_WLAN : 0;
} else if (type == NETIF_TAP) {
    my_log(INFO, "found tun/tap interface %s", ifaddr->ifa_name);
} else if (type == NETIF_BONDING) {
    my_log(INFO, "found bond interface %s", ifaddr->ifa_name);
} else if (type == NETIF_BRIDGE) {
    my_log(INFO, "found bridge interface %s", ifaddr->ifa_name);
    sysinfo->cap |= CAP_BRIDGE; 
    sysinfo->cap_active |= (enabled == 1) ? CAP_BRIDGE : 0;
} else if (type == NETIF_VLAN) {
    my_log(INFO, "found vlan interface %s", ifaddr->ifa_name);
} else if (type == NETIF_INVALID) {
    my_log(INFO, "skipping interface %s", ifaddr->ifa_name);
    continue;
}

完整文件位于此处: 此处

于 2012-10-30T14:44:09.100 回答