How to retrieve eth0 id programmatically How to retrieve eth0 id programmatically unix unix

How to retrieve eth0 id programmatically


Use the if_nametoindex() function.

unsigned int idx = if_nametoindex("eth0");if (idx == 0) {    perror("if_nametoindex"); }


The standard linux c library for handling network interfaces is getifaddrs.

You can get a linked list of the existing interfaces from getifaddrs and count them till you find the one you're looking for.

Other than that it is not completely clear why you need that number (I am getting the XY problem hunch). I'm saying that because the OS differs the interfaces by name.