Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3323046
  • 博文数量: 366
  • 博客积分: 9916
  • 博客等级: 中将
  • 技术积分: 7194
  • 用 户 组: 普通用户
  • 注册时间: 2011-05-29 23:27
个人简介

简单!

文章分类

全部博文(366)

文章存档

2013年(51)

2012年(269)

2011年(46)

分类: C/C++

2012-01-11 11:39:54

获取网口流量信息的代码如下:

  1. #define TXBYTE        0
  2. #define TXPACKET    1
  3. #define RXBYTE        2
  4. #define RXPACKET    3

  5. static inline char *strip_space(char *str)
  6. {
  7.     while (*str == ' ')
  8.         str++;
  9.     return str;
  10. }

  11. char* getField(char *a_line, char *delim, int count)
  12. {
  13.     int i = 0;
  14.     char *tok;
  15.     tok = strtok(a_line, delim);
  16.     while (tok)
  17.     {
  18.         if (i == count)
  19.             break;
  20.         i++;
  21.         tok = strtok(NULL, delim);
  22.     }
  23.     if (tok && isdigit(*tok))
  24.         return tok;

  25.     return NULL;
  26. }

  27. static long long getIfStatistic(char *interface, int type)
  28. {
  29.     int found_flag = 0;
  30.     int skip_line = 2;
  31.     char buf[1024], *field, *semiColon = NULL;
  32.     FILE *fp = fopen("/proc/net/dev", "r");
  33.     if (!fp)
  34.     {
  35.         printf("no proc?\n");
  36.         return -1;
  37.     }

  38.     while (fgets(buf, 1024, fp))
  39.     {
  40.         char *ifname;
  41.         if (skip_line != 0)
  42.         {
  43.             skip_line--;
  44.             continue;
  45.         }
  46.         if (!(semiColon = strchr(buf, ':')))
  47.             continue;
  48.         *semiColon = '\0';
  49.         ifname = buf;
  50.         ifname = strip_space(ifname);

  51.         if (!strcmp(ifname, interface))
  52.         {
  53.             found_flag = 1;
  54.             break;
  55.         }
  56.     }
  57.     fclose(fp);

  58.     semiColon++;

  59.     switch (type)
  60.     {
  61.         case TXBYTE:
  62.             if ((field = getField(semiColon, " ", 8)))
  63.             {
  64.                 return strtoll(field, NULL, 10);
  65.             }
  66.             break;
  67.         case TXPACKET:
  68.             if ((field = getField(semiColon, " ", 9)))
  69.             {
  70.                 return strtoll(field, NULL, 10);
  71.             }
  72.             break;
  73.         case RXBYTE:
  74.             if ((field = getField(semiColon, " ", 0)))
  75.             {
  76.                 return strtoll(field, NULL, 10);
  77.             }
  78.             break;
  79.         case RXPACKET:
  80.             if ((field = getField(semiColon, " ", 1)))
  81.             {
  82.                 return strtoll(field, NULL, 10);
  83.             }
  84.             break;
  85.     }
  86.     return -1;
  87. }

阅读(1130) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~