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

/*
* 作者:杨志永
* 日期: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;
	float result_of_download;
	float result_of_upload;

	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:");
		result_of_download = (float)(end_download_speed-start_download_speed)/(SECOND*1000);
		result_of_upload = (float)(end_upload_speed-start_upload_speed)/(SECOND*1000);
		if (result_of_download > 1000.0 && result_of_upload > 1000.0)
		{
			printf("下载速度: %.2f MB/s\t", result_of_download/1000);
			printf("上传速度: %.2f MB/s\n",result_of_upload/1000);
		}
		else if (result_of_download > 1000.0 )
		{
			printf("下载速度: %.2f MB/s\t", result_of_download/1000);
			printf("上传速度: %.2f KB/s\n",result_of_upload);
			
		}
		else if (result_of_upload > 1000.0 )
		{
			printf("下载速度: %.2f KB/s\t", result_of_download);
			printf("上传速度: %.2f MB/s\n",result_of_upload/1000);
			
		}
		else
		{
			printf("下载速度: %.2f KB/s\t", result_of_download);
			printf("上传速度: %.2f KB/s\n",result_of_upload);
		}
	}	
	
	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;	

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值