转自http://blog.csdn.net/ljy520yzy/article/details/7558933
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
/***************************************************** * * 作者:杨志永 * 日期: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; } |