这个片段可以帮助你,它比我想象的更复杂:
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;
}
完整文件位于此处:
此处