2 * ifstat.c handy utility to read net interface statistics
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
9 * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
22 #include <sys/socket.h>
31 #include <libnetlink.h>
32 #include <linux/netdevice.h>
37 int reset_history = 0;
38 int ignore_history = 0;
41 int scan_interval = 0;
42 int time_constant = 0;
48 char info_source[128];
51 #define MAXS (sizeof(struct net_device_stats)/sizeof(unsigned long))
55 struct ifstat_ent *next;
58 unsigned long long val[MAXS];
60 unsigned long ival[MAXS];
63 struct ifstat_ent *kern_db;
64 struct ifstat_ent *hist_db;
66 static int match(const char *id)
73 for (i=0; i<npatterns; i++) {
74 if (!fnmatch(patterns[i], id, 0))
80 static int get_nlmsg(const struct sockaddr_nl *who,
81 struct nlmsghdr *m, void *arg)
83 struct ifinfomsg *ifi = NLMSG_DATA(m);
84 struct rtattr * tb[IFLA_MAX+1];
85 int len = m->nlmsg_len;
89 if (m->nlmsg_type != RTM_NEWLINK)
92 len -= NLMSG_LENGTH(sizeof(*ifi));
96 if (!(ifi->ifi_flags&IFF_UP))
99 parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len);
100 if (tb[IFLA_IFNAME] == NULL || tb[IFLA_STATS] == NULL)
103 n = malloc(sizeof(*n));
106 n->ifindex = ifi->ifi_index;
107 n->name = strdup(RTA_DATA(tb[IFLA_IFNAME]));
108 memcpy(&n->ival, RTA_DATA(tb[IFLA_STATS]), sizeof(n->ival));
109 memset(&n->rate, 0, sizeof(n->rate));
110 for (i=0; i<MAXS; i++)
111 n->val[i] = n->ival[i];
119 struct ifstat_ent *db, *n;
120 struct rtnl_handle rth;
122 if (rtnl_open(&rth, 0) < 0)
125 if (rtnl_wilddump_request(&rth, AF_INET, RTM_GETLINK) < 0) {
126 perror("Cannot send dump request");
130 if (rtnl_dump_filter(&rth, get_nlmsg, NULL, NULL, NULL) < 0) {
131 fprintf(stderr, "Dump terminated\n");
148 void load_raw_table(FILE *fp)
151 struct ifstat_ent *db = NULL;
152 struct ifstat_ent *n;
154 while (fgets(buf, sizeof(buf), fp) != NULL) {
160 buf[strlen(buf)-1] = 0;
161 if (info_source[0] && strcmp(info_source, buf+1))
163 strncpy(info_source, buf+1, sizeof(info_source)-1);
166 if ((n = malloc(sizeof(*n))) == NULL)
169 if (!(p = strchr(buf, ' ')))
173 if (sscanf(buf, "%d", &n->ifindex) != 1)
175 if (!(next = strchr(p, ' ')))
182 for (i=0; i<MAXS; i++) {
184 if (!(next = strchr(p, ' ')))
187 if (sscanf(p, "%llu", n->val+i) != 1)
189 n->ival[i] = (unsigned long)n->val[i];
191 if (!(next = strchr(p, ' ')))
194 if (sscanf(p, "%u", &rate) != 1)
211 void dump_raw_db(FILE *fp, int to_hist)
213 struct ifstat_ent *n, *h;
215 fprintf(fp, "#%s\n", info_source);
217 for (n=kern_db; n; n=n->next) {
219 unsigned long long *vals = n->val;
220 double *rates = n->rate;
221 if (!match(n->name)) {
222 struct ifstat_ent *h1;
225 for (h1 = h; h1; h1 = h1->next) {
226 if (h1->ifindex == n->ifindex) {
234 fprintf(fp, "%d %s ", n->ifindex, n->name);
235 for (i=0; i<MAXS; i++)
236 fprintf(fp, "%llu %u ", vals[i], (unsigned)rates[i]);
241 /* use communication definitions of meg/kilo etc */
242 static const unsigned long long giga = 1000000000ull;
243 static const unsigned long long mega = 1000000;
244 static const unsigned long long kilo = 1000;
246 void format_rate(FILE *fp, unsigned long long *vals, double *rates, int i)
250 fprintf(fp, "%7lluM ", vals[i]/mega);
251 else if (vals[i] > mega)
252 fprintf(fp, "%7lluK ", vals[i]/kilo);
254 fprintf(fp, "%8llu ", vals[i]);
256 if (rates[i] > mega) {
257 sprintf(temp, "%uM", (unsigned)(rates[i]/mega));
258 fprintf(fp, "%-6s ", temp);
259 } else if (rates[i] > kilo) {
260 sprintf(temp, "%uK", (unsigned)(rates[i]/kilo));
261 fprintf(fp, "%-6s ", temp);
263 fprintf(fp, "%-6u ", (unsigned)rates[i]);
266 void format_pair(FILE *fp, unsigned long long *vals, int i, int k)
270 fprintf(fp, "%7lluM ", vals[i]/mega);
271 else if (vals[i] > mega)
272 fprintf(fp, "%7lluK ", vals[i]/kilo);
274 fprintf(fp, "%8llu ", vals[i]);
276 if (vals[k] > giga) {
277 sprintf(temp, "%uM", (unsigned)(vals[k]/mega));
278 fprintf(fp, "%-6s ", temp);
279 } else if (vals[k] > mega) {
280 sprintf(temp, "%uK", (unsigned)(vals[k]/kilo));
281 fprintf(fp, "%-6s ", temp);
283 fprintf(fp, "%-6u ", (unsigned)vals[k]);
286 void print_head(FILE *fp)
288 fprintf(fp, "#%s\n", info_source);
289 fprintf(fp, "%-15s ", "Interface");
291 fprintf(fp, "%8s/%-6s ", "RX Pkts", "Rate");
292 fprintf(fp, "%8s/%-6s ", "TX Pkts", "Rate");
293 fprintf(fp, "%8s/%-6s ", "RX Data", "Rate");
294 fprintf(fp, "%8s/%-6s\n","TX Data", "Rate");
297 fprintf(fp, "%-15s ", "");
298 fprintf(fp, "%8s/%-6s ", "RX Errs", "Drop");
299 fprintf(fp, "%8s/%-6s ", "TX Errs", "Drop");
300 fprintf(fp, "%8s/%-6s ", "RX Over", "Rate");
301 fprintf(fp, "%8s/%-6s\n","TX Coll", "Rate");
303 fprintf(fp, "%-15s ", "");
304 fprintf(fp, "%8s/%-6s ", "RX Errs", "Rate");
305 fprintf(fp, "%8s/%-6s ", "RX Drop", "Rate");
306 fprintf(fp, "%8s/%-6s ", "RX Over", "Rate");
307 fprintf(fp, "%8s/%-6s\n","RX Leng", "Rate");
309 fprintf(fp, "%-15s ", "");
310 fprintf(fp, "%8s/%-6s ", "RX Crc", "Rate");
311 fprintf(fp, "%8s/%-6s ", "RX Frm", "Rate");
312 fprintf(fp, "%8s/%-6s ", "RX Fifo", "Rate");
313 fprintf(fp, "%8s/%-6s\n","RX Miss", "Rate");
315 fprintf(fp, "%-15s ", "");
316 fprintf(fp, "%8s/%-6s ", "TX Errs", "Rate");
317 fprintf(fp, "%8s/%-6s ", "TX Drop", "Rate");
318 fprintf(fp, "%8s/%-6s ", "TX Coll", "Rate");
319 fprintf(fp, "%8s/%-6s\n","TX Carr", "Rate");
321 fprintf(fp, "%-15s ", "");
322 fprintf(fp, "%8s/%-6s ", "TX Abrt", "Rate");
323 fprintf(fp, "%8s/%-6s ", "TX Fifo", "Rate");
324 fprintf(fp, "%8s/%-6s ", "TX Hear", "Rate");
325 fprintf(fp, "%8s/%-6s\n","TX Wind", "Rate");
329 void print_one_if(FILE *fp, struct ifstat_ent *n, unsigned long long *vals)
332 fprintf(fp, "%-15s ", n->name);
334 format_rate(fp, vals, n->rate, i);
338 fprintf(fp, "%-15s ", "");
339 format_pair(fp, vals, 4, 6);
340 format_pair(fp, vals, 5, 7);
341 format_rate(fp, vals, n->rate, 11);
342 format_rate(fp, vals, n->rate, 9);
345 fprintf(fp, "%-15s ", "");
346 format_rate(fp, vals, n->rate, 4);
347 format_rate(fp, vals, n->rate, 6);
348 format_rate(fp, vals, n->rate, 11);
349 format_rate(fp, vals, n->rate, 10);
352 fprintf(fp, "%-15s ", "");
353 format_rate(fp, vals, n->rate, 12);
354 format_rate(fp, vals, n->rate, 13);
355 format_rate(fp, vals, n->rate, 14);
356 format_rate(fp, vals, n->rate, 15);
359 fprintf(fp, "%-15s ", "");
360 format_rate(fp, vals, n->rate, 5);
361 format_rate(fp, vals, n->rate, 7);
362 format_rate(fp, vals, n->rate, 9);
363 format_rate(fp, vals, n->rate, 17);
366 fprintf(fp, "%-15s ", "");
367 format_rate(fp, vals, n->rate, 16);
368 format_rate(fp, vals, n->rate, 18);
369 format_rate(fp, vals, n->rate, 19);
370 format_rate(fp, vals, n->rate, 20);
376 void dump_kern_db(FILE *fp)
378 struct ifstat_ent *n, *h;
383 for (n=kern_db; n; n=n->next) {
386 print_one_if(fp, n, n->val);
391 void dump_incr_db(FILE *fp)
393 struct ifstat_ent *n, *h;
398 for (n=kern_db; n; n=n->next) {
400 unsigned long long vals[MAXS];
401 struct ifstat_ent *h1;
403 memcpy(vals, n->val, sizeof(vals));
405 for (h1 = h; h1; h1 = h1->next) {
406 if (h1->ifindex == n->ifindex) {
407 for (i = 0; i < MAXS; i++)
408 vals[i] -= h1->val[i];
415 print_one_if(fp, n, vals);
422 void sigchild(int signo)
426 void update_db(int interval)
428 struct ifstat_ent *n, *h;
438 for (n = kern_db; n; n = n->next) {
439 struct ifstat_ent *h1;
440 for (h1 = h; h1; h1 = h1->next) {
441 if (h1->ifindex == n->ifindex) {
443 for (i = 0; i < MAXS; i++) {
444 if ((long)(h1->ival[i] - n->ival[i]) < 0) {
445 memset(n->ival, 0, sizeof(n->ival));
449 for (i = 0; i < MAXS; i++) {
451 unsigned long incr = h1->ival[i] - n->ival[i];
453 n->ival[i] = h1->ival[i];
454 sample = (double)(incr*1000)/interval;
455 if (interval >= scan_interval) {
456 n->rate[i] += W*(sample-n->rate[i]);
457 } else if (interval >= 1000) {
458 if (interval >= time_constant) {
461 double w = W*(double)interval/scan_interval;
462 n->rate[i] += w*(sample-n->rate[i]);
468 struct ifstat_ent *tmp = h;
482 #define T_DIFF(a,b) (((a).tv_sec-(b).tv_sec)*1000 + ((a).tv_usec-(b).tv_usec)/1000)
485 void server_loop(int fd)
487 struct timeval snaptime = { 0 };
490 p.events = p.revents = POLLIN;
492 sprintf(info_source, "%d.%lu sampling_interval=%d time_const=%d",
493 getpid(), (unsigned long)random(), scan_interval/1000, time_constant/1000);
502 gettimeofday(&now, NULL);
503 tdiff = T_DIFF(now, snaptime);
504 if (tdiff >= scan_interval) {
510 if (poll(&p, 1, tdiff + scan_interval) > 0
511 && (p.revents&POLLIN)) {
512 int clnt = accept(fd, NULL, NULL);
517 } else if ((pid = fork()) != 0) {
522 FILE *fp = fdopen(clnt, "w");
532 while (children && waitpid(-1, &status, WNOHANG) > 0)
537 int verify_forging(int fd)
540 socklen_t olen = sizeof(cred);
542 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, (void*)&cred, &olen) ||
545 if (cred.uid == getuid() || cred.uid == 0)
550 static void usage(void) __attribute__((noreturn));
552 static void usage(void)
555 "Usage: ifstat [OPTION] [ PATTERN [ PATTERN ] ]\n"
556 " -h, --help this message\n"
557 " -a, --ignore ignore history\n"
558 " -d, --scan=SECS sample every statistics every SECS\n"
559 " -e, --errors show errors\n"
560 " -n, --nooutput do history only\n"
561 " -r, --reset reset history\n"
562 " -s, --noupdate don;t update history\n"
563 " -t, --interval=SECS report average over the last SECS\n"
564 " -V, --version output version information\n"
565 " -z, --zeros show entries with zero activity\n"
566 " -e, --errors show errors\n"
567 " -z, --zeros show entries with zero activity\n");
572 static const struct option longopts[] = {
573 { "help", 0, 0, 'h' },
574 { "ignore", 0, 0, 'a' },
575 { "scan", 1, 0, 'd'},
576 { "errors", 0, 0, 'e' },
577 { "nooutput", 0, 0, 'n' },
578 { "reset", 0, 0, 'r' },
579 { "noupdate", 0, 0, 's' },
580 { "interval", 1, 0, 't' },
581 { "version", 0, 0, 'V' },
582 { "zeros", 0, 0, 'z' },
583 { "errors", 0, 0, 'e' },
584 { "zeros", 0, 0, 'z' },
588 int main(int argc, char *argv[])
591 struct sockaddr_un sun;
592 FILE *hist_fp = NULL;
596 while ((ch = getopt_long(argc, argv, "hvVzrnasd:t:eK",
597 longopts, NULL)) != EOF) {
618 scan_interval = atoi(optarg) * 1000;
619 if (scan_interval <= 0) {
620 fprintf(stderr, "ifstat: invalid scan interval\n");
625 time_constant = atoi(optarg);
626 if (time_constant <= 0) {
627 fprintf(stderr, "ifstat: invalid time constant divisor\n");
633 printf("ifstat utility, iproute2-ss%s\n", SNAPSHOT);
645 sun.sun_family = AF_UNIX;
647 sprintf(sun.sun_path+1, "ifstat%d", getuid());
649 if (scan_interval > 0) {
650 if (time_constant == 0)
652 time_constant *= 1000;
653 W = 1 - 1/exp(log(10)*(double)scan_interval/time_constant);
654 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
655 perror("ifstat: socket");
658 if (bind(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) < 0) {
659 perror("ifstat: bind");
662 if (listen(fd, 5) < 0) {
663 perror("ifstat: listen");
669 close(0); close(1); close(2); setsid();
670 signal(SIGPIPE, SIG_IGN);
671 signal(SIGCHLD, sigchild);
679 if (getenv("IFSTAT_HISTORY"))
680 snprintf(hist_name, sizeof(hist_name), getenv("IFSTAT_HISTORY"));
682 sprintf(hist_name, "%s/.ifstat.u%d", P_tmpdir, getuid());
687 if (!ignore_history || !no_update) {
690 fd = open(hist_name, O_RDWR|O_CREAT|O_NOFOLLOW, 0600);
692 perror("ifstat: open history file");
695 if ((hist_fp = fdopen(fd, "r+")) == NULL) {
696 perror("ifstat: fdopen history file");
699 if (flock(fileno(hist_fp), LOCK_EX)) {
700 perror("ifstat: flock history file");
703 if (fstat(fileno(hist_fp), &stb) != 0) {
704 perror("ifstat: fstat history file");
707 if (stb.st_nlink != 1 || stb.st_uid != getuid()) {
708 fprintf(stderr, "ifstat: something is so wrong with history file, that I prefer not to proceed.\n");
711 if (!ignore_history) {
714 if ((tfp = fopen("/proc/uptime", "r")) != NULL) {
715 if (fscanf(tfp, "%ld", &uptime) != 1)
719 if (uptime >= 0 && time(NULL) >= stb.st_mtime+uptime) {
720 fprintf(stderr, "ifstat: history is aged out, resetting\n");
721 ftruncate(fileno(hist_fp), 0);
725 load_raw_table(hist_fp);
731 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) >= 0 &&
732 (connect(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) == 0
733 || (strcpy(sun.sun_path+1, "ifstat0"),
734 connect(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) == 0))
735 && verify_forging(fd) == 0) {
736 FILE *sfp = fdopen(fd, "r");
738 if (hist_db && source_mismatch) {
739 fprintf(stderr, "ifstat: history is stale, ignoring it.\n");
746 if (hist_db && info_source[0] && strcmp(info_source, "kernel")) {
747 fprintf(stderr, "ifstat: history is stale, ignoring it.\n");
752 if (info_source[0] == 0)
753 strcpy(info_source, "kernel");
757 if (ignore_history || hist_db == NULL)
758 dump_kern_db(stdout);
760 dump_incr_db(stdout);
763 ftruncate(fileno(hist_fp), 0);
765 dump_raw_db(hist_fp, 1);