[英]Finding an interface name from an IP address
我需要通過提供 IP 地址來獲取接口名稱。 沒有系統調用可以得到這個。
我需要在 C 或 C++ 中為此實現
Stack Overflow, Find an IP address from an interface name上已經提供了相反的方法。
使用getifaddrs(3)
。 簡單的例子。 用法“./foo 123.45.67.89”請添加錯誤檢查等:
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <ifaddrs.h>
int main(int argc, char *argv[]) {
struct ifaddrs *addrs, *iap;
struct sockaddr_in *sa;
char buf[32];
getifaddrs(&addrs);
for (iap = addrs; iap != NULL; iap = iap->ifa_next) {
if (iap->ifa_addr && (iap->ifa_flags & IFF_UP) && iap->ifa_addr->sa_family == AF_INET) {
sa = (struct sockaddr_in *)(iap->ifa_addr);
inet_ntop(iap->ifa_addr->sa_family, (void *)&(sa->sin_addr), buf, sizeof(buf));
if (!strcmp(argv[1], buf)) {
printf("%s\n", iap->ifa_name);
}
}
}
freeifaddrs(addrs);
return 0;
}
你能簡單地解析類似的輸出嗎?
netstat -ie | grep -B1 "192.168.21.10"
-B1部分告訴grep我們想要在輸出中包含匹配前的行,所以我們得到:
eth0 Link encap:Ethernet HWaddr 00:13:72:79:65:23
inet addr:192.168.21.10 Bcast:192.168.21.255 Mask:255.255.255.0
一旦你有信心就可以得到你需要的輸出,你可以將它進一步濃縮成一個單線......
netstat -ie | grep -B1 "192.168.21.10" | head -n1 | awk '{print $1}'
只返回“eth0”
更可靠:
netstat -ie | grep -B1 ":10.2.34.3 " | head -n1 | awk '{print $1}'
netstat -ie | grep -B1 "<ip-address>"
必須小心使用netstat -ie | grep -B1 "<ip-address>"
,因為如果你有多個網絡適配器,例如IP1= 210.2.3.4 (eth0)
和IP2=10.2.3.4 (eth1)
IP1= 210.2.3.4 (eth0)
IP2=10.2.3.4 (eth1)
,那么命令netstat -ie | grep -B1 "10.2.3.4"
netstat -ie | grep -B1 "10.2.3.4"
會找到兩個適配器。 但預期的結果只有一個。
所以更可靠的版本是:
netstat -ie | grep -B1 ":<ip-address> "
(注意最后的空白 - 這是故意的)
有時, ip route list
可能足以過濾接口並提供整潔的輸出。 它不是基於“IP 地址”而是基於它所屬的網絡。
ip route list 10.9.0.0/24 | awk '{print $3}'
eno2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.