C语言实现ifconfig获取网卡接收和发送流量统计

               

Windows下我们可以利用ipconfig命令获取网卡的相关信息,在Linux下命令是ifconfig

我们可以获取的信息更为丰富,其中包括网卡接收和发送的流量,用C语言实现这个命令并不是一件简单的事,由此,博主经查阅相关资料,得知,网卡的相关信息保存在 /proc/net/dev  这个文件夹下,所以,我们可以通过读取这个文件里的信息获取相应网卡的信息。

这个文件包含四部分内容,分别是:发送包的个数,发送的流量,接收包的个数,接收的流量,同时,由于网络环境在不断的变化之中,所以,这个文件的内容也是在实时更新的。

下面这张图片显示的是 ifconfig 命令的实现结果


注意,其中有许多参数,这些参数并不保存在文件中

下面是博主实现的一段C语言代码获取接收和发送的流量

重要的地方已经给出了注释

#include <stdio.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <unistd.h>#include <stdlib.h>long *my_ipconfig(char *ath0){        int nDevLen = strlen(ath0);    if (nDevLen < 1 || nDevLen > 100)    {        printf("dev length too long\n");        return NULL;    }    int fd = open("/proc/net/dev", O_RDONLY | O_EXCL);    if (-1 == fd)    {        printf("/proc/net/dev not exists!\n");        return NULL;    }            char buf[1024*2];        lseek(fd, 0, SEEK_SET);        int nBytes = read(fd, buf, sizeof(buf)-1);        if (-1 == nBytes)        {            perror("read error");            close(fd);            return NULL;        }        buf[nBytes] = '\0';        //返回第一次指向ath0位置的指针        char* pDev = strstr(buf, ath0);        if (NULL == pDev)        {            printf("don't find dev %s\n", ath0);            return NULL;        }        char *p;        char *ifconfig_value;        int i = 0;        static long rx2_tx10[2];  /*去除空格,制表符,换行符等不需要的字段*/        for (p = strtok(pDev, " \t\r\n"); p; p = strtok(NULL, " \t\r\n"))        {      i++;      ifconfig_value = (char*)malloc(20);      strcpy(ifconfig_value, p);   /*得到的字符串中的第二个字段是接收流量*/      if(i == 2)      {       rx2_tx10[0] = atol(ifconfig_value);      }   /*得到的字符串中的第十个字段是发送流量*/      if(i == 10)      {       rx2_tx10[1] = atol(ifconfig_value);       break;      }      free(ifconfig_value);    }    return rx2_tx10;}int main()long *ifconfig_result; double re_mb;  /*eth0 是博主计算机上的网卡的名字*/ ifconfig_result = my_ipconfig("eth0");  /*保存在文件中的数值的单位是B,经过计算换算成MB*/    re_mb = (double)ifconfig_result[0]/(1024*1024);    printf("接收流量:%0.2f MB\n",re_mb);     /*保存在文件中的数值的单位是B,经过计算换算成MB*/    re_mb = (double)ifconfig_result[1]/(1024*1024);    printf("发送流量:%0.2f MB\n",re_mb); }

保存文件的名字为 dele.c

运行相关的命令:

gcc -o dele dele.c

./dele

得到结果如下图所示


由此得到了网卡的接收和发送流量

           

猜你喜欢

转载自blog.csdn.net/qq_44919483/article/details/89490017
今日推荐