欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

获取硬盘和网卡流量  

程序员文章站 2022-07-14 10:11:15
...
#include <sys/vfs.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <string>
#include <assert.h>

using std::string;

string DiskCapacity(const string &path)
{
    assert(path.size() > 0);
    char disk_capacity[128];
    struct statfs st;
    int ret = statfs(path.c_str(), &st);
    if (ret == 0) {
		float freeCap = (1.0 * st.f_bsize * st.f_bavail) / (1024*1024*1024);
		float totalCap = (1.0 * st.f_bsize * st.f_blocks) / (1024*1024*1024);
		snprintf(disk_capacity, 128, "%.2f", freeCap);

    } else  {
        return "0";
    }

	return string(disk_capacity);
}

int64_t NetworkLoad()
{
	int64_t recv_bytes = 0;
	int64_t ethX_count = 0;
	size_t len = 0;
	ssize_t read;

	FILE* fp;
	fp = fopen("/proc/net/dev", "r");
	if (fp == NULL) {
	   printf("open /proc/net/dev fail errmsg=%s", strerror(errno));
           return 0;
	}

	char * line = NULL;
	while ((read = getline(&line, &len, fp)) != -1) {
		string line_str = line;
		string::size_type eth_pos;
		if ( (eth_pos = line_str.find("eth") ) != string::npos ) {
			string::size_type space_pos_t =  line_str.find(' ', eth_pos + 5);
			if (space_pos_t != string::npos) {
				recv_bytes += atol(line_str.substr(eth_pos + 5, space_pos_t - eth_pos - 5).c_str());
			}
			ethX_count++;
		}
	}
	if (line) 
		free(line);

	fclose(fp);

	return recv_bytes / ethX_count ; 
}

int main(int argc,char* argv[])
{
	printf("%s,%d", DiskCapacity("/").c_str(), NetworkLoad()/1024 );

}