Linux/bsd中检测网卡是否为虚拟网卡(docker/veth/etc)

Gag*_*n93 5 networking ubuntu virtual-network

我在这个页面上看到了一些关于在 ubuntu 中获取有关网卡及其统计信息的很好的解释。正如页面上提到的,这提供了一个很好的输出。我也尝试阅读其他文档,但找不到可以区分系统上真实网卡和虚拟网卡的标志或类似内容。

有没有办法区分?谢谢。

Lac*_*cek 6

检查/sys/class/net/<device_name>符号链接。如果它指向/sys/devices/virtual/,则它是一个虚拟接口。如果它指向一个“真实的”设备(例如 into /sys/devices/pci0000:00/),则它不是。

编辑:

从代码中,您可以readlink用来检查设备是否是虚拟的。这是一个非常虚拟的示例代码:

#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>

int main(int argc, char **argv) {
    char theLink[128];
    char thePath[128];

    strcpy(thePath,"/sys/class/net/");
    memset(theLink,0,128);

    if (argc>1) {
        strcat(thePath,argv[1]);
    } else {
        printf("Gimme device\n");
        return 1;
    }

    if (readlink(thePath, theLink, 127)==-1) {
        perror(argv[1]);
    } else {
        if (strstr(theLink,"/virtual")) {
            printf("%s is a virtual device\n",argv[1]);
        } else {
            printf("%s is a physical device\n",argv[1]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)