Home > other >  How to detect if a tun/tap device already exists
How to detect if a tun/tap device already exists

Time:04-23

I want to create a tun device with the code, so before creating it I want to check if the tun device already exists

Right now I'm doing this by determining if the file already exists, but this method is not graceful

Is there a better way

    char tun_dev_name[IFNAMSIZ   15];
    for(int tun_num = 0; ;tun_num  )
    {
        sprintf(ifr.ifr_name, "tun%d", tun_num);
        //TODO it is not graceful
        sprintf(tun_dev_name, "/sys/class/net/%s", ifr.ifr_name);
        if(access(tun_dev_name, F_OK) != 0 )
            break;
    }

CodePudding user response:

If you ask the kernel for an interface name with a %d in it, the kernel will choose a number for you and you won't need to do this.

See documentation which includes an example program with this comment:

char *dev should be the name of the device with a format string (e.g. "tun%d"), but (as far as I can see) this can be any valid network device name.
Note that the character pointer becomes overwritten with the real device name (e.g. "tun0")

As the comment says, after you execute TUNSETIFF to set the interface name with a format string, the buffer is overwritten with the name the kernel selected. Make sure it's large enough - IFNAMSIZ bytes including null terminator.

  • Related