获取路由器网络信息(mac,ip,router,dns,dhcp clients)

1.获取接口的mac地址


char *get_macaddr(char *ifname)
{
    struct ifreq ifr;
    char *ptr;
    int skfd;
    static char if_hw[18] = {0};

    if((skfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        fprintf(stderr, "%s: open socket error\n", __func__);
        return NULL;
    }
    strncpy(ifr.ifr_name, ifname, IF_NAMESIZE);
    if(ioctl(skfd, SIOCGIFHWADDR, &ifr) < 0) {
        close(skfd);
        fprintf(stderr, "%s: ioctl fail\n", __func__);
        return NULL;
    }

    ptr = (char *)&ifr.ifr_addr.sa_data;
    sprintf(if_hw, "%02X:%02X:%02X:%02X:%02X:%02X",
            (ptr[0] & 0377), (ptr[1] & 0377), (ptr[2] & 0377),
            (ptr[3] & 0377), (ptr[4] & 0377), (ptr[5] & 0377));
    close(skfd);

    return if_hw;
}

2.获取接口的IP地址


/*
 * arguments: ifname  - interface name
 *            if_addr - a 16-byte buffer to store ip address
 * description: fetch ip address, netmask associated to given interface name
 */
int getIfIp(char *ifname, char *if_addr)
{
    struct ifreq ifr;
    int skfd = 0;

    if((skfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        return -1;
    }

    strncpy(ifr.ifr_name, ifname, IF_NAMESIZE);
    if (ioctl(skfd, SIOCGIFADDR, &ifr) < 0) {
        close(skfd);
        return -1;
    }
    strcpy(if_addr, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

    close(skfd);

    return 0;
}

3.获取接口的子网掩码


/*
 * arguments: ifname - interface name
 *            if_net - a 16-byte buffer to store subnet mask
 * description: fetch subnet mask associated to given interface name
 *              0 = bridge, 1 = gateway, 2 = wirelss isp
 */
int getIfNetmask(char *ifname, char *if_net)
{
    struct ifreq ifr;
    int skfd = 0;

    if((skfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        return -1;
    }
    strncpy(ifr.ifr_name, ifname, IF_NAMESIZE);

    if (ioctl(skfd, SIOCGIFNETMASK, &ifr) < 0) {
        close(skfd);
        return -1;
    }

    strcpy(if_net, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

    close(skfd);

    return 0;
}

4.获取路由IP


/*
 * description: write WAN default gateway accordingly
 */
static int getWanGateway(char *routerIP)
{
    char   buff[256];
    int    nl = 0 ;
    struct in_addr dest;
    struct in_addr gw;
    int    flgs, ref, use, metric;
    unsigned long int d,g,m;
    int    find_default_flag = 0;

    char sgw[16];

    FILE *fp = fopen("/proc/net/route", "r");

    while (fgets(buff, sizeof(buff), fp) != NULL) {
        if (nl) {
            int ifl = 0;
            while (buff[ifl]!=' ' && buff[ifl]!='\t' && buff[ifl]!='\0')
                ifl++;
            buff[ifl]=0;    /* interface */
            if (sscanf(buff+ifl+1, "%lx%lx%X%d%d%d%lx",&d, &g, &flgs, &ref, &use, &metric, &m)!=7) {
                fclose(fp);
                return -1;
            }

            if (flgs&RTF_UP) {
                dest.s_addr = d;
                gw.s_addr   = g;
                strcpy(sgw, (gw.s_addr==0 ? "" : inet_ntoa(gw)));

                if (dest.s_addr == 0) {
                    find_default_flag = 1;
                    break;
                }
            }
        }
        nl++;
    }
    fclose(fp);

    if (find_default_flag == 1){
        if(routerIP !=NULL)
            strcpy(routerIP,sgw);
        return 1;
    }
    else
        return -1;
}

5.获取连接到本路由器终端数的具体信息


struct  ClientInfoStruct{

    char name[32];
    char ip[32];
    char mac[32];
    int rcvCount;
    int sndCount;

} ;



/*
 * description: write DHCP client list
 */
static int getDhcpCliList(struct ClientInfoStruct **infoArr, int *arrLen)
{
    FILE *fp;
    int i = 0;
    int n = 0;
    char  buff[256];
    char *dhcpclients[5];

    fp = fopen("/tmp/dhcp.leases", "r");

    if (NULL == fp)
        return -1;

    while (fgets(buff, sizeof(buff), fp) != NULL) {

     char delims[] = " ";
   char *result = NULL;


    // printf("str = %s \n",buff);
     buff[strlen(buff)-1]='\0';

   result = strtok(buff,delims );
   i = 0;
   while( result != NULL ) {
       result = strtok( NULL, delims );
       dhcpclients[i] = result;
      // printf( "dhcpclients[%d] is \"%s\"\n", i,dhcpclients[i]);
      i++;
   }   

   strcpy(infoArr[n]->mac,dhcpclients[0]);
   strcpy(infoArr[n]->ip,dhcpclients[1]);
   strcpy(infoArr[n]->name,dhcpclients[2]);

     printf("infoArr[%d]->mac= %s \n",n,infoArr[n]->mac);
     printf("infoArr[%d]->ip= %s \n",n,infoArr[n]->ip);
     printf("infoArr[%d]->name= %s \n",n,infoArr[n]->name);

   n++;         

    }

    *arrLen = n;

    fclose(fp);

    return 0;
}

6.获取路由器dns信息


static int getDns(int type,char *nameserver)
{
    FILE *fp;
    char buf[80] = {0}, ns_str[11], dns[16] = {0};
    int idx = 0, req = 0;


    if (1 == type)
            req = 1;
    else if (2 == type)
            req = 2;
    else
            return -1;

    fp = fopen("/etc/resolv.conf", "r");

    if (NULL == fp)
        return -1;

    while(fgets(buf, sizeof(buf), fp) != NULL) {

        if(strncmp(buf, "nameserver", 10) != 0)
            continue;

        sscanf(buf, "%s%s", ns_str, dns);

        strcpy(nameserver,dns);

        idx++;

        if(idx == req)
            break;
    }

    fclose(fp);

    return 1;
}

完整实例

注意二级指针传回值的初始化:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include  
#include 
#include  
#include 


char *get_macaddr(char *ifname)
{
    struct ifreq ifr;
    char *ptr;
    int skfd;
    static char if_hw[18] = {0};

    if((skfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        fprintf(stderr, "%s: open socket error\n", __func__);
        return NULL;
    }
    strncpy(ifr.ifr_name, ifname, IF_NAMESIZE);
    if(ioctl(skfd, SIOCGIFHWADDR, &ifr) < 0) {
        close(skfd);
        fprintf(stderr, "%s: ioctl fail\n", __func__);
        return NULL;
    }

    ptr = (char *)&ifr.ifr_addr.sa_data;
    sprintf(if_hw, "%02X:%02X:%02X:%02X:%02X:%02X",
            (ptr[0] & 0377), (ptr[1] & 0377), (ptr[2] & 0377),
            (ptr[3] & 0377), (ptr[4] & 0377), (ptr[5] & 0377));
    close(skfd);

    return if_hw;
}

static int getDns(int type,char *nameserver)
{
    FILE *fp;
    char buf[80] = {0}, ns_str[11], dns[16] = {0};
    int idx = 0, req = 0;


    if (1 == type)
            req = 1;
    else if (2 == type)
            req = 2;
    else
            return -1;

    fp = fopen("/etc/resolv.conf", "r");

    if (NULL == fp)
        return -1;

    while(fgets(buf, sizeof(buf), fp) != NULL) {

        if(strncmp(buf, "nameserver", 10) != 0)
            continue;

        sscanf(buf, "%s%s", ns_str, dns);

        strcpy(nameserver,dns);

        idx++;

        if(idx == req)
            break;
    }

    fclose(fp);

    return 1;
}


/*
 * arguments: ifname - interface name
 *            if_net - a 16-byte buffer to store subnet mask
 * description: fetch subnet mask associated to given interface name
 *              0 = bridge, 1 = gateway, 2 = wirelss isp
 */
int getIfNetmask(char *ifname, char *if_net)
{
    struct ifreq ifr;
    int skfd = 0;

    if((skfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        return -1;
    }
    strncpy(ifr.ifr_name, ifname, IF_NAMESIZE);

    if (ioctl(skfd, SIOCGIFNETMASK, &ifr) < 0) {
        close(skfd);
        return -1;
    }

    strcpy(if_net, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

    close(skfd);

    return 0;
}


/*
 * arguments: ifname  - interface name
 *            if_addr - a 16-byte buffer to store ip address
 * description: fetch ip address, netmask associated to given interface name
 */
int getIfIp(char *ifname, char *if_addr)
{
    struct ifreq ifr;
    int skfd = 0;

    if((skfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        return -1;
    }

    strncpy(ifr.ifr_name, ifname, IF_NAMESIZE);
    if (ioctl(skfd, SIOCGIFADDR, &ifr) < 0) {
        close(skfd);
        return -1;
    }
    strcpy(if_addr, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

    close(skfd);

    return 0;
}


/*
 * description: write WAN default gateway accordingly
 */
static int getWanGateway(char *routerIP)
{
    char   buff[256];
    int    nl = 0 ;
    struct in_addr dest;
    struct in_addr gw;
    int    flgs, ref, use, metric;
    unsigned long int d,g,m;
    int    find_default_flag = 0;

    char sgw[16];

    FILE *fp = fopen("/proc/net/route", "r");

    while (fgets(buff, sizeof(buff), fp) != NULL) {
        if (nl) {
            int ifl = 0;
            while (buff[ifl]!=' ' && buff[ifl]!='\t' && buff[ifl]!='\0')
                ifl++;
            buff[ifl]=0;    /* interface */
            if (sscanf(buff+ifl+1, "%lx%lx%X%d%d%d%lx",&d, &g, &flgs, &ref, &use, &metric, &m)!=7) {
                fclose(fp);
                return -1;
            }

            if (flgs&RTF_UP) {
                dest.s_addr = d;
                gw.s_addr   = g;
                strcpy(sgw, (gw.s_addr==0 ? "" : inet_ntoa(gw)));

                if (dest.s_addr == 0) {
                    find_default_flag = 1;
                    break;
                }
            }
        }
        nl++;
    }
    fclose(fp);

    if (find_default_flag == 1){
        if(routerIP !=NULL)
            strcpy(routerIP,sgw);
        return 1;
    }
    else
        return -1;
}

struct  ClientInfoStruct{

    char name[32];
    char ip[32];
    char mac[32];
    int rcvCount;
    int sndCount;

} ;



/*
 * description: write DHCP client list
 */
static int getDhcpCliList(struct ClientInfoStruct **infoArr, int *arrLen)
{
    FILE *fp;
    int i = 0;
    int n = 0;
    char  buff[256];
    char *dhcpclients[5];

    fp = fopen("/tmp/dhcp.leases", "r");

    if (NULL == fp)
        return -1;

    while (fgets(buff, sizeof(buff), fp) != NULL) {

     char delims[] = " ";
   char *result = NULL;


    // printf("str = %s \n",buff);
     buff[strlen(buff)-1]='\0';

   result = strtok(buff,delims );
   i = 0;
   while( result != NULL ) {
       result = strtok( NULL, delims );
       dhcpclients[i] = result;
      // printf( "dhcpclients[%d] is \"%s\"\n", i,dhcpclients[i]);
      i++;
   }   

   strcpy(infoArr[n]->mac,dhcpclients[0]);
   strcpy(infoArr[n]->ip,dhcpclients[1]);
   strcpy(infoArr[n]->name,dhcpclients[2]);

     printf("infoArr[%d]->mac= %s \n",n,infoArr[n]->mac);
     printf("infoArr[%d]->ip= %s \n",n,infoArr[n]->ip);
     printf("infoArr[%d]->name= %s \n",n,infoArr[n]->name);

   n++;         

    }

    *arrLen = n;

    fclose(fp);

    return 0;
}



int main(){

    printf("test ok! \n");
    char *routerip = (char *)malloc(32);
    char *ip = (char *)malloc(32);
    char *netmask = (char *)malloc(32);
    char *mac = NULL;

    //通过二级指针传回函数值

    struct ClientInfoStruct **infoArr;

    infoArr = (struct ClientInfoStruct **)malloc(sizeof(struct ClientInfoStruct *)*64);
    int k =0;
    for(k=0;k<64;k++){
        infoArr[k] = (struct ClientInfoStruct *)malloc(sizeof(struct ClientInfoStruct));
    }

    getWanGateway(routerip);
    printf("router ip = %s \n",routerip);


  getIfIp("eth0",ip);
    printf("ip = %s \n",ip);


    getIfNetmask("eth0",netmask);
    printf("netmask = %s \n",netmask);


    mac = get_macaddr("eth0");
    printf("mac = %s \n",mac);

    getDns(1,ip);
    printf("dns 1 = %s \n",ip);

    getDns(2,ip);
    printf("dns 2 = %s \n",ip);

    int len;
    getDhcpCliList(infoArr,&len);


    printf("_________________________________________________________________ \n");
    for(k=0;kprintf("infoArr[%d]->mac= %s \n",k,infoArr[k]->mac);
      printf("infoArr[%d]->ip= %s \n",k,infoArr[k]->ip);
        printf("infoArr[%d]->name= %s \n",k,infoArr[k]->name);


    }

    free(routerip);
        routerip = NULL;

    free(ip);
        ip = NULL;


    free(netmask);
        netmask = NULL;


    return 0;   
}

你可能感兴趣的:(Linux网络编程)