设为首页 加入收藏

TOP

C语言实现ifconfig获取网卡接收和发送流量统计 (一)
2014-11-23 22:04:19 来源: 作者: 【 】 浏览:84
Tags:语言 实现 ifconfig 获取 网卡 接收 发送 流量 统计

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

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

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

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

\


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

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

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


[cpp] view plaincopyprint
#include
#include
#include
#include
#include
#include
#include

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);

}

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

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(p

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇c语言 ++ ―― 下一篇C语言中scanf/fscanf 的%[]和%n说..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: