1.if_nameindex进行网卡扫描
1.结构体
net/if.h头文件
结构体:struct if_nameindex
struct if_nameindex
{
unsigned int if_index; //网卡索引
char *if_name; //网卡名称
};
网卡名称宏定义如下:
/* Length of interface name. */
#define IF_NAMESIZE 16
#2.函数
1)使用if_nameindex()接口可以扫描当前设备上的所有网卡名称
/* Return a list of all interfaces and their indices. */
extern struct if_nameindex *if_nameindex (void) __THROW;
返回值:
成功返回数组的指针;失败返回空指针,并且设置对应的错误码给errno。
2)通过if_nameindex()获取完毕接口名称与索引后,调用该函数以释放动态分配的内存区域
/* Free the data returned from if_nameindex. */
extern void if_freenameindex (struct if_nameindex *__ptr) __THROW;
#3.源码
获取网络列表源码如下:
#include <net/if.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
struct if_nameindex *if_ni, *i;
if_ni = if_nameindex();
if (if_ni == NULL) {
perror("if_nameindex");
exit(EXIT_FAILURE);
}
for (i = if_ni; ! (i->if_index == 0 && i->if_name == NULL); i++)
printf("%u: %s\n", i->if_index, i->if_name);
if_freenameindex(if_ni);
exit(EXIT_SUCCESS);
}
2.c 判定指定网口是否存在
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <net/if.h>
int interface_exists(const char *interface_name) {
struct if_nameindex *interfaces;
unsigned int i;
interfaces = if_nameindex();
if (interfaces == NULL) {
perror("if_nameindex");
return -1; // Error
}
for (i = 0; interfaces[i].if_index != 0; ++i) {
if (strcmp(interfaces[i].if_name, interface_name) == 0) {
// Interface found
free(interfaces);
return 1; // Exists
}
}
// Interface not found
free(interfaces);
return 0; // Does not exist
}
int main() {
const char *interface = "eth0"; // Specify the interface you want to check
int exists = interface_exists(interface);
if (exists == 1) {
printf("Interface %s exists.\n", interface);
} else if (exists == 0) {
printf("Interface %s does not exist.\n", interface);
} else {
printf("Error checking for interface %s.\n", interface);
}
return 0;
}