转自:https://blog.csdn.net/dosthing/article/details/80384541

前言

网络编程是程序连接网络拓展的基础,尤其是在物联网、互联网加等概念火热的当下,网络编程能力体现了一个程序员能否具有大型程序的开发能力。在实际应用中,往往需要显示目前系统的实时网速等信息,当然获取网速等信息的软件方法很多,但是用小几行代码,并可移植性好的方法却不多,这里介绍如何通过Linux的proc文件系统进行实时获取网卡收发速率。

原理简介

Linux提供的LKM机制可以使我们通过proc伪文件系统来获取Linux内核信息,而通过proc/net/dev我们可以实时获取网络适配器及统计信息。抛开复杂的概念,简单说就是我们可以利用proc/net/dev来获取网卡的网速及网络包的收发情况。这里我们主要关心Receive和Transmit项的bytes项。bytes定义:The total number of bytes of datatransmitted or received by the interface. 即网口的发送或接收的数据的总字节数。更多选项的定义,我们用不着,如有兴趣了解戳这里。

实例详解

有了以上的背景知识,足够我们理解实例的内容了,直接上源码,看看如何实现实时统计网卡的网速信息。

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <dirent.h>
#include <time.h>
#include <fcntl.h>
#include <errno.h>

#ifdef debugprintf
#define debugpri(mesg, args...) fprintf(stderr, "[NetRate print:%s:%d:] " mesg "\n", __FILE__, __LINE__, ##args)
#else
#define debugpri(mesg, args...)
#endif

int GetNetRate(FILE* fd,char *interface,long *recv,long *send)
{
char buf[1024];
char *p;
char flow[32];
int i = 0;
char tempstr[16][16]={0};

memset(buf,0,sizeof(buf));
memset(tempstr,0,sizeof(tempstr));
fseek(fd, 0, SEEK_SET);
int nBytes = fread(buf,1, sizeof(buf)-1,fd);
if (-1 == nBytes)
{
debugpri("fread error");
fclose(fd);
return -1;
}
buf[nBytes] = '\0';
char* pDev = strstr(buf, interface);
if (NULL == pDev)
{
printf("don't find dev %s\n", interface);
fclose(fd);
return -1;
}
sscanf(pDev,"%[^' ']\t%[^' ']\t%[^' ']\t%[^' ']\t%[^' ']\t%[^' ']\t%[^' ']\t%[^' ']\t%[^' ']\t%[^' ']\t%[^' ']\t%[^' ']\t",\
tempstr[0],tempstr[1],tempstr[2],tempstr[3],tempstr[4],tempstr[5],tempstr[6],tempstr[7],tempstr[8],tempstr[9],tempstr[10],tempstr[11]);
*recv = atol(tempstr[1]);
*send = atol(tempstr[9]);
}
int main(int argc, char** argv)
{
struct timeval tv_now,tv_pre;
char netdevice[16]={0};
int nDevLen;
long recvpre = 0,recvcur = 0;
long sendpre = 0,sendcur = 0;
double sendrate;
double recvrate;

if(argc != 2)
{
printf("Usage: netrate <network device>\n");
exit(0);
}

nDevLen = strlen(argv[1]);
if (nDevLen < 1 || nDevLen > 10)
{
printf("unkown device\n");
exit(0);
}
sprintf(netdevice,"%s",argv[1]);
FILE* fd = fopen("/proc/net/dev","r+");
if (NULL == fd)
{
debugpri("/proc/net/dev not exists!\n");
return -1;
}
while(1)
{
gettimeofday(&tv_pre,NULL);
GetNetRate(fd,netdevice,&recvpre,&sendpre);
sleep(2);
gettimeofday(&tv_now,NULL);
GetNetRate(fd,netdevice,&recvcur,&sendcur);
recvrate= (recvcur - recvpre)/(1024*(tv_now.tv_sec+tv_now.tv_usec*0.000001-tv_pre.tv_sec+tv_pre.tv_usec*0.000001));
if(recvrate<0)
{
recvrate = 0;
}
sendrate= (sendcur - sendpre)/(1024*(tv_now.tv_sec+tv_now.tv_usec*0.000001-tv_pre.tv_sec+tv_pre.tv_usec*0.000001));
if(sendrate<0)
{
sendrate = 0;
}
system("clear");
printf("NetWorkRate Statistic Verson 0.0.1\n");
printf("Net Device receive rate send rate\n");
printf("%-10s\t%-6.2fKB/sec\t%-6.2fKB/sec\n",netdevice,recvrate,recvrate);
}
fclose(fd);
return 0;
}

总结:

物联网、互联网加的蓬勃发展,产品的功能实现越来越依赖网络,掌握一些网络编程的小技巧,可以使得我们在产品开发中能够事半功倍,提升软实力。今天是5月20日,在特殊的日子里整理一下知识,以做备忘,原创不易,转载说明文章出处。番外篇,我把上面的实例程序整理成了一个网络小工具,很实用,在主流的Linux平台编译运行没有任何的warning警告,如需要嵌入式移植开发或者其他用途请点此下载。

---------------------
作者:dosthing
来源:CSDN
原文:https://blog.csdn.net/dosthing/article/details/80384541
版权声明:本文为博主原创文章,转载请附上博文链接!

proc/net/dev实时网速统计实例【转】的更多相关文章

  1. proc/net/dev实时网速统计实例

    https://blog.csdn.net/dosthing/article/details/80384541 http://www.l99.com/EditText_view.action?text ...

  2. TrafficStats——流量统计类的范例,获取实时网速

    2.3开始android就提供来这个类的API,这样我们就可以方便的用他来实现统计手机流量来.这个类其实也很简单,我贴上他的几个方法,大家一看就知道怎么用了. static long getMobil ...

  3. C# 实现实时网速

    前言 最近参加了一个项目,所以写博客的时间就少了,项目中有一个功能就是在窗体上显示实时网速,用了半天的时间写了出来,想想今天时间蛮充足,就把它分享到博客上吧. 项目展示 项目核心代码: private ...

  4. 【Linux环境编程】获取网卡的实时网速

    在windows以下.我们能够看到360或者是qq安全卫士的"安全球".上面显示实时的网速情况.那么在linux里面怎样获取网卡的实时网速?事实上原理非常easy,读取须要获取网速 ...

  5. Android中获取实时网速(2)

    一.实现思路: 1.Android提供有获取当前总流量的方法 2.上一秒 减去 下一面的流量差便是网速 3.注意计算 二.计算网速的工具类: package imcs.cb.com.viewappli ...

  6. python检测当前网卡流量信息,用于查看实时网速

    可以用来检测是否有挖矿程序在运行的一个子条件 # coding:utf-8 __author__ = 'chenhuachao' import wmi import time import platf ...

  7. Ubuntu 16.04安装基于nethogs衍生的网络监控软件(应用实时网速监控)

    基于nethogs衍生的网络监控软件有如下所列举的: nettop显示数据包类型,按数据包的大小或数量排序. ettercap是以太网的网络嗅探器/拦截器/记录器 darkstat通过主机,协议等方式 ...

  8. nload 实时网速查看

    nload eth0 -u K Device eth0 [192.168.0.33] (1/1):=================================================== ...

  9. Ubuntu显示实时网速CPU内存等参数

    添加库 sudo add-apt-repository ppa:fossfreedom/indicator-sysmonitor 更新软件列表 sudo apt-get update 安装indica ...

随机推荐

  1. linux 优化(一)

    uptime up 表示系统正在运行 10:54:19 表示当前时间 8 min 表示系统启动的总时间 1 user 表示正在登陆用户数 load average 表示系统平均负载,最后三个数字呢,依 ...

  2. ipv4转化为ipv6

    十進制轉換成十六進位 IPV6為十六進位,所以十進制轉換成十六進位192=c0 168=a8192.168.1.1 轉成 16 進制為 c0.a8.01.01可以使用 Windows 工程版或是程式設 ...

  3. 【JS】JS格式化文件大小 单位:Bytes、KB、MB、GB

    输入一个表示文件大小的数字,自适应转换到KB,MB,GB 方法一:bytes自适应转换到KB,MB,GB /// <summary> /// 格式化文件大小的JS方法 /// </s ...

  4. UVA - 1401 | LA 3942 - Remember the Word(dp+trie)

    https://vjudge.net/problem/UVA-1401 题意 给出S个不同的单词作为字典,还有一个长度最长为3e5的字符串.求有多少种方案可以把这个字符串分解为字典中的单词. 分析 首 ...

  5. ZOJ - 1610 Count the Colors(线段树区间更新)

    https://cn.vjudge.net/problem/ZOJ-1610 题意 给一个n,代表n次操作,接下来每次操作表示把[l,r]区间的线段涂成k的颜色其中,l,r,k的范围都是0到8000. ...

  6. php中inset 和 和 empty 的区别

    inset函数 用途:检测变量是否设置判断:检测变量是否设置,并且不是 NULL.如果已经使用 unset() 释放了一个变量之后,它将不再是 isset().若使用 isset() 测试一个被设置成 ...

  7. Lua的协程基础

    参考:Lua中的协同程序 coroutine   http.lua 协同程序(Coroutine): 三个状态:suspended(挂起,协同刚创建完成时或者yield之后).running(运行). ...

  8. 细说shiro之自定义filter

    写在前面 我们知道,shiro框架在Java Web应用中使用时,本质上是通过filter方式集成的. 也就是说,它是遵循过滤器链规则的:filter的执行顺序与在web.xml中定义的顺序一致,如下 ...

  9. ASP.NET Web API 2 过滤器

    Ø  前言 我们知道 ASP.NET Web API 过滤器,也是属于消息处理机制中的一部分.正因如此,我们经常使用它来完成对请求的授权验证.参数验证,以及请求的 Log 记录,程序异常捕获等. 1. ...

  10. GCC编译器原理(一)------交叉编译器制作和GCC组件及命令

    1.1 交叉编译器制作 默认安装的 GCC 编译系统所产生的代码适用于本机,即运行 GCC 的机器,但也可将 GCC 安装成能够生成其他的机器代码.安装一些必须的模块,就可产生多种目标机器代码,而且可 ...