File: mrtg-ip-acct.c

package info (click to toggle)
mrtgutils 0.8.3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, stretch
  • size: 124 kB
  • ctags: 42
  • sloc: ansic: 497; makefile: 32
file content (51 lines) | stat: -rw-r--r-- 1,161 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "uptime.h"
#include "util.h"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

void print_ipacct(char *dev, int packets)
{
  char buf[1024];
  char *p;
  FILE *f;
  unsigned long long in = 0, out = 0;

  f = fopen("/proc/net/dev", "r");
  if (!f) {
        fprintf(stderr, "mrtg-ip-acct:error: Error reading /proc/net/dev\n");
        exit(2);
  }
  while (fgets(buf, sizeof(buf), f)) {
    p = buf;
    while (isspace(*p)) p++;
    if (strncmp(dev, p, strlen(dev)) == 0) {
      while (*p != ':') p++; p++;
      if (packets)
        sscanf(p, "%*d %Lu %*d %*d %*d %*d %*d %*d %*d %Lu %*d %*d %*d %*d %*d %*d", &in, &out);
      else
        sscanf(p, "%Lu %*d %*d %*d %*d %*d %*d %*d %Lu %*d %*d %*d %*d %*d %*d %*d", &in, &out);
    }
  }
  fclose(f);
  
  printf("%Lu\n%Lu\n", in, out);
}
  
int main(int argc, char **argv)
{
  char *device = "eth0";
  int packets = 0;
  int nextarg = 1;
  if (argc > nextarg && !strncmp(argv[nextarg], "-p", 3)) {
    packets = 1;
    ++nextarg;
  }
  if (argc > nextarg) device = argv[nextarg];
  
  print_ipacct(device, packets);
  print_uptime();
  print_hostname();
  return 0;
}