Detect if a network card is a virtual network card (docker/veth/etc) in Linux / bsd

Solution 1:

Check the /sys/class/net/<device_name> symlink. If it points into /sys/devices/virtual/, then it is a virtual interface. If it points to a "real" device (e.g. into /sys/devices/pci0000:00/), then it is not.

Edit:

From code, you can use readlink to check if the device is virtual. Here is a very dummy sample code to do so:

#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]);
        }
    }
}