/*
* 作者:杨志永
* 日期: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;
}
Linux C下获取下载和上传的网速V2
最新推荐文章于 2022-11-27 12:31:59 发布