您的位置:首页 > 运维架构 > Linux

Linux C下获取下载和上传的网速V2

2012-05-11 22:52 155 查看
/*
* 作者:杨志永
* 日期:2012-04-17 10:10
* Email:ljy520zhiyong@163.com
* QQ:929168233
*
* 文件名: watch_network_speed.c
* 编译环境:Debian 6.0.4 Testing, GCC 4.6.3 X86_64
*
* 功能:获取Linux系统下的下载和上传的网速
*
*/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>

#define BUFFER 1024
#define SECOND 1
int get_net_work_download_speed(long int * download_speed, long int * upload_speed, char * download_type, char * upload_type);

int main(int argc, char * argv[])
{
long int start_download_speed;
long int end_download_speed;
long int start_upload_speed;
long int end_upload_speed;

while (1)
{
get_net_work_download_speed(&start_download_speed, &start_upload_speed, "RX bytes:", "TX bytes:");
sleep(SECOND);
get_net_work_download_speed(&end_download_speed, &end_upload_speed, "RX bytes:", "TX bytes:");
printf("下载速度: %.2lf KB/s\t", (float)(end_download_speed-start_download_speed)/(SECOND*1000));
printf("上传速度: %.2lf KB/s\n", (float)(end_upload_speed-start_upload_speed)/(SECOND*1000));
}
exit(EXIT_SUCCESS);
}

int get_net_work_download_speed(long int * download_speed, long int * upload_speed, char * download_type, char * upload_type)
{
FILE * pipo_stream;
size_t bytes_read;

char buffer[BUFFER];
char * match;

if ( (pipo_stream=popen("sudo ifconfig", "r")) == NULL )
{
printf("pipo error!\n");
return -1;
}

bytes_read = fread(buffer, 1, sizeof(buffer), pipo_stream);

if ( (fclose(pipo_stream)) != 0 )
{
printf("fclose error!\n");
return -1;
}

if ( bytes_read == 0 )
{
printf("bytes_read == 0\n");
return -1;
}

match = strstr(buffer, download_type);

if (match == NULL)
{
printf("NO Keyword %s To Find!\n", download_type);
return -1;
}

sscanf(match, "RX bytes:%ld", download_speed);

match = strstr(buffer, upload_type);
if (match == NULL)
{
printf("No Keyword %s To Find!\n", upload_type);
return -1;
}
sscanf(match, "TX bytes:%ld", upload_speed);
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐