转自 http://blog.csdn.net/ljy520yzy/article/details/7558933
/*****************************************************
*
* 作者:杨志永
* 日期:2012-4-16 4:35PM
* E-mail:ljy520zhiyong@163.com
* QQ:929168233
*
* filename: watch_net_speed.c
* 编译环境:Debian 6.0.4 Testing + GCC 4.6.3 X86_64
*
*****************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define WAIT_SECOND 3 // 暂停时间,单位为“秒”long int getCurrentDownloadRates(long int * save_rate); // 获取当前的流量,参数为将获取到的流量保存的位置
int main(int argc, char * argv[])
{
long int start_download_rates; // 保存开始时的流量计数
long int end_download_rates; // 保存结果时的流量计数
while(1)
{getCurrentDownloadRates(&start_download_rates);// 获取当前流量,并保存在 start_download_rates 里
sleep(WAIT_SECOND); // 休眠多少秒,这个值根据宏定义中的 WAIT_SECOND 的值来确定
//sleep 的头文件在 unistd.h
getCurrentDownloadRates(&end_download_rates);// 获取当前流量,并保存在 end_download_rates 里
printf("download is : %.2lf Bytes/s\n", (float)(end_download_rates-start_download_rates)/WAIT_SECOND );// 打印结果
}
exit(EXIT_SUCCESS);
}
long int getCurrentDownloadRates(long int * save_rate)
{
FILE * net_dev_file; // 文件指针
char buffer[1024]; // 文件中的内容暂存在字符缓冲区里
size_t bytes_read; // 实际读取的内容大小
char * match; // 用以保存所匹配字符串及之后的内容
if ((net_dev_file=fopen("/proc/net/dev", "r")) == NULL ) // 打开文件 /pro/net/dev/,我们要读取的数据就是它啦
{printf("open file /proc/net/dev/ error!\n");
exit(EXIT_FAILURE);
}
bytes_read = fread(buffer, 1, sizeof(buffer), net_dev_file);// 将文件中的 1024 个字符大小的数据保存到 buffer 里
fclose(net_dev_file); // 关闭文件
if (bytes_read == 0)// 如果文件内容大小为0,没有数据则退出
{exit(EXIT_FAILURE);
}
buffer[bytes_read] = '\0';
match = strstr(buffer, "eth0:");// 匹配 eth0 第一次出现的位置,返回值为第一次出现的位置的地址
if (match == NULL)
{printf("no eth0 keyword to find!\n");
exit(EXIT_FAILURE);
}
sscanf(match, "eth0:%ld", save_rate);// 从字符缓冲里读取数据,这个值就是当前的流量啦。呵呵。return *save_rate;
}
正文完