如何从接口ip地址获取接口索引

谁能告诉我如何从接口IP地址获取接口索引? 例如,如果接口IP地址是192.168.23.25,那接口索引是什么。

我想补充一点,我需要使用它在一个代码写在C,所以如果任何function有一些选项可以给我的接口索引号的基础上的接口IP地址。

你应该可以用getifaddrs()来做到这一点。 它应该解释MarkR对二级地址的担忧。 作为一个测试,

添加这样的东西后:

ip addr add 192.168.25.23/24 dev eth0 

编译和运行手册页上的示例程序应该显示如下内容:

 lo address family: 17 (AF_PACKET) eth0 address family: 17 (AF_PACKET) lo address family: 2 (AF_INET) address: <127.0.0.1> eth0 address family: 2 (AF_INET) address: <192.168.1.105> eth0 address family: 2 (AF_INET) address: <192.168.25.23> lo address family: 10 (AF_INET6) address: <::1> eth0 address family: 10 (AF_INET6) address: <fe84::82d6:baaf:fe14:4c22%eth0> 

您应该能够在遍历列表时获取索引,但是您还可以查看if_nametoindex() , if_indextoname()和if_nameindex()函数。 由于您可以将地址与接口名称关联起来,因此您可以根据需要调用这些地址。

你不能这样做,你必须查看所有的接口,然后遍历所有的IP地址,直到找到你想要的。 我认为这个代码做你想要的。

 #include <sys/ioctl.h> #include <net/if.h> #include <netinet/in.h> #include <stdio.h> #include <arpa/inet.h> int main(int argc, char *argv[]) { in_addr_t ia; int id; ia = inet_addr(argv[1]); id = do_lookup(ia); } int do_lookup(in_addr_t ia) { char buf[1024]; struct ifconf ifc; struct ifreq *ifr; int sck; int nInterfaces; int i; /* Get a socket handle. */ sck = socket(AF_INET, SOCK_DGRAM, 0); if(sck < 0) { perror("socket"); return -1; } /* Query available interfaces. */ ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; if(ioctl(sck, SIOCGIFCONF, &ifc) < 0) { perror("ioctl(SIOCGIFCONF)"); return -1; } /* Iterate through the list of interfaces. */ ifr = ifc.ifc_req; nInterfaces = ifc.ifc_len / sizeof(struct ifreq); for(i = 0; i < nInterfaces; i++) { struct ifreq *item = &ifr[i]; if(((struct sockaddr_in *)&item->ifr_addr)->sin_addr.s_addr == ia) { return i; } } return -1; } 

你可以使用这个: 它将列出您的Linux机器上的网络接口。

  #include <sys/ioctl.h> #include <net/if.h> #include <netinet/in.h> #include <stdio.h> #include <arpa/inet.h> int main(void) { char buf[1024]; struct ifconf ifc; struct ifreq *ifr; int sck; int nInterfaces; int i; /* Get a socket handle. */ sck = socket(AF_INET, SOCK_DGRAM, 0); if(sck < 0) { perror("socket"); return 1; } /* Query available interfaces. */ ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; if(ioctl(sck, SIOCGIFCONF, &ifc) < 0) { perror("ioctl(SIOCGIFCONF)"); return 1; } /* Iterate through the list of interfaces. */ ifr = ifc.ifc_req; nInterfaces = ifc.ifc_len / sizeof(struct ifreq); for(i = 0; i < nInterfaces; i++) { struct ifreq *item = &ifr[i]; /* Show the device name and IP address */ printf("%s: IP %s", item->ifr_name, inet_ntoa(((struct sockaddr_in *)&item->ifr_addr)->sin_addr)); /* Get the MAC address */ if(ioctl(sck, SIOCGIFHWADDR, item) < 0) { perror("ioctl(SIOCGIFHWADDR)"); return 1; } /* Get the broadcast address (added by Eric) */ if(ioctl(sck, SIOCGIFBRDADDR, item) >= 0) printf(", BROADCAST %s", inet_ntoa(((struct sockaddr_in *)&item->ifr_broadaddr)->sin_addr)); printf("\n"); } return 0; } 

我从这里得到它

SIOCGIFCONF不会为使用添加的辅助IP地址而削减它

 ip addr add 192.168.25.23/24 dev eth1 

如果你真的需要这样做,那么看看什么“ip addr sh”使用 – 可能是一个netlink套接字操作(这涉及到真正奇怪的宏)