红联Linux门户
Linux帮助

Linux下获取第一个网络接口名称的函数实现

发布时间:2008-08-18 16:10:39来源:红联作者:Dnirta
以下代码摘自开源程序--------iftop

引用:
/* This is a list of interface name prefixes which are `bad' in the sense
* that they don't refer to interfaces of external type on which we are
* likely to want to listen. We also compare candidate interfaces to lo. */
static char *bad_interface_names[] = {
"lo:",
"lo",
"stf", /* pseudo-device 6to4 tunnel interface */
"gif", /* psuedo-device generic tunnel interface */
"dummy",
"vmnet",
NULL /* last entry must be NULL */
};

static int is_bad_interface_name(char *i) {
char **p;
for (p = bad_interface_names; *p; ++p)
if (strncmp(i, *p, strlen(*p)) == 0)
return 1;
return 0;
}

/* This finds the first interface which is up and is not the loopback
* interface or one of the interface types listed in bad_interface_names. */
static char *get_first_interface(void) {
struct if_nameindex * nameindex;
char *i = NULL;
int j = 0;
/* Use if_nameindex(3) instead? */

nameindex = if_nameindex();
if(nameindex == NULL) {
return NULL;
}

while(nameindex[j].if_index != 0) {
if (strcmp(nameindex[j].if_name, "lo") != 0 && !is_bad_interface_name(nameindex[j].if_name)) {
i = xstrdup(nameindex[j].if_name);
break;
}
j++;
}
if_freenameindex(nameindex);
return i;
}


补充说明:

struct if_nameindex

这个变量用于存储单个网络界面的信息,其中具有两个元素:

unsigned int if_index:界面序号

char *if_name:用null结尾的界面名称

struct if_nameindex *if_nameindex(void);

返回一个struct if_nameindex列表,其中存储了所有界面的信息,最后一个if_nameindex的if_index序号为零,if_name为null

此函数得到的结果必需用if_freenameindex函数清除

void if_freenameindex(struct if_nameindex *ptr);

清除if_nameindex得到的结果
文章评论

共有 0 条评论