#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<net/if.h>

static char *bad_interface_names[] = {
            "lo:",
            "lo",
            "stf",     /* pseudo-device 6to4 tunnel interface */
            "gif",     /* psuedo-device generic tunnel interface */
            "dummy",
            "vmnet",
            NULL        /* last entry must be NULL */
        };

static int is_bad_interface_name(char *i) {
    char **p;
    for (p = bad_interface_names; *p; ++p)
        if (strncmp(i, *p, strlen(*p)) == 0)
            return 1;
    return 0;
}
   
/* This finds the first interface which is up and is not the loopback
* interface or one of the interface types listed in bad_interface_names. */
static char *get_first_interface(void) {
    struct if_nameindex * nameindex;
    char *i = NULL;
    int j = 0;
    /* Use if_nameindex(3) instead? */

    nameindex = if_nameindex();
    if(nameindex == NULL) {
        return NULL;
    }

    while(nameindex[j].if_index != 0) {
        if (strcmp(nameindex[j].if_name, "lo") != 0 && !is_bad_interface_name(nameindex[j].if_name)) {
            //i = xstrdup(nameindex[j].if_name);
            break;
        }
        j++;
    }
    if_freenameindex(nameindex);
    return i;
}

 

 

 

struct if_nameindex {
      unsigned int   if_index;
      char          *if_name;
       };//结构提

 

Logo

更多推荐