linux,qux网卡重名判断

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值