谁能告诉我如何从接口ip地址获取接口索引?例如,如果接口ip地址是192.168.23.25,那么它的接口索引是什么。
我想补充的是,我需要在一个用c编写的代码中使用它,所以如果任何函数和某个选项可以根据接口ip地址给出接口索引号。
发布于 2010-03-08 05:56:22
您应该能够使用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()函数。由于您将能够将地址与接口名称相关联,因此您可以根据需要调用这些名称。
发布于 2010-03-07 20:45:48
您不能这样做,您必须查看所有接口,然后遍历所有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;
}
发布于 2018-04-04 10:07:22
以编程方式使用if_nametoindex()。我已经在Ubuntu 12.04 (内核3.11.0-15-generic)上验证了这一点。
以下是示例代码片段,
#include <net/if.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[])
{
for (int ix=1; ix<argc; ix++)
{
unsigned int rc = if_nametoindex(argv[ix]);
if (rc) {
printf("interface [%s] has index : %d\n", argv[ix], rc);
}
else {
perror("if_nametoindex");
}
}
}
使用示例:
$ ./if_index eth0
interface [eth0] has index : 2
此外,非编程方法是读取/proc/net/if_inet6条目。第二列是相应的接口索引。
$ cat /proc/net/if_inet6
00000000000000000000000000000001 01 80 10 80 lo
fe800000000000000a0027fffe1a2a32 03 40 20 80 eth1
fe800000000000000a0027fffe08b9ca 02 40 20 80 eth0
https://stackoverflow.com/questions/2396081
复制相似问题