linux下获取网络流量的实现方法

仅是通过/proc/net/dev读取其中的数据.(转载)

 

#include
#include
#include

void skipline(FILE *f)
{
  int ch;
  do {
    ch = getc(f);
  } while ( ch != 'n' && ch != EOF );
}

int main(int argc, char *argv[])
{
  FILE *pnd;
  char buffer[BUFSIZ];
  char *interface;
  struct ifinfo {
    char name[8];
    unsigned int r_bytes, r_pkt, r_err, r_drop, r_fifo, r_frame;
    unsigned int r_compr, r_mcast;
    unsigned int x_bytes, x_pkt, x_err, x_drop, x_fifo, x_coll;
    unsigned int x_carrier, x_compr;
  } ifc;
  unsigned long long bin, bout, lbin, lbout;
  int first;

  if ( argc != 2 ) {
    fprintf(stderr, "Usage: %s interfacen", argv[0]);
    exit(1);
  }

  interface = argv[1];

  first = 1;
  lbin = 0; lbout = 0;

  while ( 1 ) {
    pnd = fopen("/proc/net/dev", "r");
    if ( !pnd ) {
      fprintf(stderr, "%s: /proc/net/dev: %s", argv[0], strerror(errno));
      exit(1);
    }

    /* Skip header */
    skipline(pnd);
    skipline(pnd);

    /* Get interface info */
    do {
      if ( fscanf(pnd, " %6[^:]:%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
                  &ifc.name,
                  &ifc.r_bytes, &ifc.r_pkt, &ifc.r_err, &ifc.r_drop,
                  &ifc.r_fifo, &ifc.r_frame, &ifc.r_compr, &ifc.r_mcast,
                  &ifc.x_bytes, &ifc.x_pkt, &ifc.x_err, &ifc.x_drop,
                  &ifc.x_fifo, &ifc.x_coll, &ifc.x_carrier, &ifc.x_compr)
           != 16 ) {
        exit(200);
      }
      skipline(pnd);
    } while ( strcmp(ifc.name, interface) );

    bin  = ifc.r_bytes + (lbin & ~0xffffffffULL);
    bout = ifc.x_bytes + (lbout & ~0xffffffffULL);

    if ( bin < lbin )
      bin += (1ULL << 32);
    if ( bout < lbout )
      bout += (1ULL << 32);

    if ( !first ) {
      printf("%d %Lu %Lun", time(NULL), (bout-lbout)*8, (bin-lbin)*8);
      fflush(stdout);
    } else {
      first = 0;
    }

    lbin = bin;  lbout = bout;

    fclose(pnd);

    sleep(1);
  }
}

 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值