net-speed

/*
 * ===========================================================================
 *
 *       Filename:  net-speed.c
 *    Description:  获取网速
 *        Version:  1.0
 *        Created:  08/29/2017 07:20:10 PM
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:   (syc),
 *        Company:  xxxx
 *
 * ===========================================================================
 */
      
    #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;  
    }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值