Pages

03 August 2011

C program to get Network interface name and index in linux

 In network programming, we often need to know the interface name(s) or index(es). I am talking about the interface index/name listed with "ifconfig -a" command. Suppose you need to know the index of the interface "eth1", what would you do? Traditional approach is open netlink socket to connect link subsystem. Frame the request to get interface index/name and write to socket and wait for reading. Read the response and extract necessary information.

If you need to know (1) just interface index from given interface name or vice versa (2) list of interface names/indexes, you do not need to write netlink socket code. You can use glibc functions to achieve this. Here I have written three sample programs, please review it. To get or track other information you need to go through netlink way.


/* This program will fetch interface name for given interface index */
#include <stdio.h>
#include <stdlib.h>
#include <net/if.h>
#include <libgen.h>


int
main(int argc, char **argv)
{
unsigned int port_index;
char if_name[IFNAMSIZ];
if (argc != 2) {
fprintf(stderr, "Usage: %s <interface index>\n", basename(argv[0]));
return 1;
}
port_index = atoi(argv[1]);
if (if_indextoname(port_index, if_name) == NULL) {
fprintf(stderr, "Invalid interface index %d\n", port_index);
return 1;
}
fprintf(stdout, "Index is %d for interface %s\n", port_index, if_name);
return 0;
}


/* This program will fetch interface index of given interface name */
#include <stdio.h>
#include <stdlib.h>
#include <net/if.h>
#include <libgen.h>


int
main(int argc, char **argv)
{
    unsigned int port_index;
    const char *if_name;
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <interface name>\n", basename(argv[0]));
        return 1;
    }
    if_name = argv[1];
    if ((port_index = if_nametoindex(if_name)) == 0) {
        fprintf(stderr, "No index found for %s interface\n", if_name);
        return 1;
    }
    fprintf(stdout, "Index is %d for interface %s\n", port_index, if_name);
    return 0;
}


/* Ths program will fetch list of indexes of interfaces */
#include <stdio.h>
#include <stdlib.h>
#include <net/if.h>
#include <libgen.h>


int
main(void)
{
    register int i;
    struct if_nameindex *ids;


    ids = if_nameindex();
    for (i=0; ids[i].if_index != 0; i++) {
        printf("%d = %s\n", ids[i].if_index, ids[i].if_name);
    }
    /* Do not forget to free the memory */
    if_freenameindex(ids);
    return 0;
}



Please put comments if you enjoy the article.

1 comment:

  1. Just what I was looking for! Thanks a lot! =D

    ReplyDelete