現在のネットワーク速度をLinux言語で取得
2139 ワード
/*****************************************************
*
* :
* :2012-4-16 4:35PM
* E-mail:[email protected]
* QQ:929168233
*
* filename: watch_net_speed.c
* :Debian 6.0.4 Testing + GCC 4.6.3 X86_64
*
*****************************************************/
#include
#include
#include
#include
#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
", (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!
");
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!
");
exit(EXIT_FAILURE);
}
sscanf(match, "eth0:%ld", save_rate);// , 。 。
return *save_rate;
}