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>
33 #include <linux/if_link.h>
38 int reset_history = 0;
39 int ignore_history = 0;
42 int scan_interval = 0;
43 int time_constant = 0;
49 char info_source[128];
52 #define MAXS (sizeof(struct rtnl_link_stats)/sizeof(__u32))
56 struct ifstat_ent *next;
59 unsigned long long val[MAXS];
64 struct ifstat_ent *kern_db;
65 struct ifstat_ent *hist_db;
67 static int match(const char *id)
74 for (i=0; i<npatterns; i++) {
75 if (!fnmatch(patterns[i], id, 0))
81 static int get_nlmsg(const struct sockaddr_nl *who,
82 struct nlmsghdr *m, void *arg)
84 struct ifinfomsg *ifi = NLMSG_DATA(m);
85 struct rtattr * tb[IFLA_MAX+1];
86 int len = m->nlmsg_len;
90 if (m->nlmsg_type != RTM_NEWLINK)
93 len -= NLMSG_LENGTH(sizeof(*ifi));
97 if (!(ifi->ifi_flags&IFF_UP))
100 parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len);
101 if (tb[IFLA_IFNAME] == NULL || tb[IFLA_STATS] == NULL)
104 n = malloc(sizeof(*n));
107 n->ifindex = ifi->ifi_index;
108 n->name = strdup(RTA_DATA(tb[IFLA_IFNAME]));
109 memcpy(&n->ival, RTA_DATA(tb[IFLA_STATS]), sizeof(n->ival));
110 memset(&n->rate, 0, sizeof(n->rate));
111 for (i=0; i<MAXS; i++)
112 n->val[i] = n->ival[i];
120 struct ifstat_ent *db, *n;
121 struct rtnl_handle rth;
123 if (rtnl_open(&rth, 0) < 0)
126 if (rtnl_wilddump_request(&rth, AF_INET, RTM_GETLINK) < 0) {
127 perror("Cannot send dump request");
131 if (rtnl_dump_filter(&rth, get_nlmsg, NULL) < 0) {
132 fprintf(stderr, "Dump terminated\n");
149 void load_raw_table(FILE *fp)
152 struct ifstat_ent *db = NULL;
153 struct ifstat_ent *n;
155 while (fgets(buf, sizeof(buf), fp) != NULL) {
161 buf[strlen(buf)-1] = 0;
162 if (info_source[0] && strcmp(info_source, buf+1))
164 strncpy(info_source, buf+1, sizeof(info_source)-1);
167 if ((n = malloc(sizeof(*n))) == NULL)
170 if (!(p = strchr(buf, ' ')))
174 if (sscanf(buf, "%d", &n->ifindex) != 1)
176 if (!(next = strchr(p, ' ')))
183 for (i=0; i<MAXS; i++) {
185 if (!(next = strchr(p, ' ')))
188 if (sscanf(p, "%llu", n->val+i) != 1)
190 n->ival[i] = (__u32)n->val[i];
192 if (!(next = strchr(p, ' ')))
195 if (sscanf(p, "%u", &rate) != 1)
212 void dump_raw_db(FILE *fp, int to_hist)
214 struct ifstat_ent *n, *h;
216 fprintf(fp, "#%s\n", info_source);
218 for (n=kern_db; n; n=n->next) {
220 unsigned long long *vals = n->val;
221 double *rates = n->rate;
222 if (!match(n->name)) {
223 struct ifstat_ent *h1;
226 for (h1 = h; h1; h1 = h1->next) {
227 if (h1->ifindex == n->ifindex) {
235 fprintf(fp, "%d %s ", n->ifindex, n->name);
236 for (i=0; i<MAXS; i++)
237 fprintf(fp, "%llu %u ", vals[i], (unsigned)rates[i]);
242 /* use communication definitions of meg/kilo etc */
243 static const unsigned long long giga = 1000000000ull;
244 static const unsigned long long mega = 1000000;
245 static const unsigned long long kilo = 1000;
247 void format_rate(FILE *fp, unsigned long long *vals, double *rates, int i)
251 fprintf(fp, "%7lluM ", vals[i]/mega);
252 else if (vals[i] > mega)
253 fprintf(fp, "%7lluK ", vals[i]/kilo);
255 fprintf(fp, "%8llu ", vals[i]);
257 if (rates[i] > mega) {
258 sprintf(temp, "%uM", (unsigned)(rates[i]/mega));
259 fprintf(fp, "%-6s ", temp);
260 } else if (rates[i] > kilo) {
261 sprintf(temp, "%uK", (unsigned)(rates[i]/kilo));
262 fprintf(fp, "%-6s ", temp);
264 fprintf(fp, "%-6u ", (unsigned)rates[i]);
267 void format_pair(FILE *fp, unsigned long long *vals, int i, int k)
271 fprintf(fp, "%7lluM ", vals[i]/mega);
272 else if (vals[i] > mega)
273 fprintf(fp, "%7lluK ", vals[i]/kilo);
275 fprintf(fp, "%8llu ", vals[i]);
277 if (vals[k] > giga) {
278 sprintf(temp, "%uM", (unsigned)(vals[k]/mega));
279 fprintf(fp, "%-6s ", temp);
280 } else if (vals[k] > mega) {
281 sprintf(temp, "%uK", (unsigned)(vals[k]/kilo));
282 fprintf(fp, "%-6s ", temp);
284 fprintf(fp, "%-6u ", (unsigned)vals[k]);
287 void print_head(FILE *fp)
289 fprintf(fp, "#%s\n", info_source);
290 fprintf(fp, "%-15s ", "Interface");
292 fprintf(fp, "%8s/%-6s ", "RX Pkts", "Rate");
293 fprintf(fp, "%8s/%-6s ", "TX Pkts", "Rate");
294 fprintf(fp, "%8s/%-6s ", "RX Data", "Rate");
295 fprintf(fp, "%8s/%-6s\n","TX Data", "Rate");
298 fprintf(fp, "%-15s ", "");
299 fprintf(fp, "%8s/%-6s ", "RX Errs", "Drop");
300 fprintf(fp, "%8s/%-6s ", "TX Errs", "Drop");
301 fprintf(fp, "%8s/%-6s ", "RX Over", "Rate");
302 fprintf(fp, "%8s/%-6s\n","TX Coll", "Rate");
304 fprintf(fp, "%-15s ", "");
305 fprintf(fp, "%8s/%-6s ", "RX Errs", "Rate");
306 fprintf(fp, "%8s/%-6s ", "RX Drop", "Rate");
307 fprintf(fp, "%8s/%-6s ", "RX Over", "Rate");
308 fprintf(fp, "%8s/%-6s\n","RX Leng", "Rate");
310 fprintf(fp, "%-15s ", "");
311 fprintf(fp, "%8s/%-6s ", "RX Crc", "Rate");
312 fprintf(fp, "%8s/%-6s ", "RX Frm", "Rate");
313 fprintf(fp, "%8s/%-6s ", "RX Fifo", "Rate");
314 fprintf(fp, "%8s/%-6s\n","RX Miss", "Rate");
316 fprintf(fp, "%-15s ", "");
317 fprintf(fp, "%8s/%-6s ", "TX Errs", "Rate");
318 fprintf(fp, "%8s/%-6s ", "TX Drop", "Rate");
319 fprintf(fp, "%8s/%-6s ", "TX Coll", "Rate");
320 fprintf(fp, "%8s/%-6s\n","TX Carr", "Rate");
322 fprintf(fp, "%-15s ", "");
323 fprintf(fp, "%8s/%-6s ", "TX Abrt", "Rate");
324 fprintf(fp, "%8s/%-6s ", "TX Fifo", "Rate");
325 fprintf(fp, "%8s/%-6s ", "TX Hear", "Rate");
326 fprintf(fp, "%8s/%-6s\n","TX Wind", "Rate");
330 void print_one_if(FILE *fp, struct ifstat_ent *n, unsigned long long *vals)
333 fprintf(fp, "%-15s ", n->name);
335 format_rate(fp, vals, n->rate, i);
339 fprintf(fp, "%-15s ", "");
340 format_pair(fp, vals, 4, 6);
341 format_pair(fp, vals, 5, 7);
342 format_rate(fp, vals, n->rate, 11);
343 format_rate(fp, vals, n->rate, 9);
346 fprintf(fp, "%-15s ", "");
347 format_rate(fp, vals, n->rate, 4);
348 format_rate(fp, vals, n->rate, 6);
349 format_rate(fp, vals, n->rate, 11);
350 format_rate(fp, vals, n->rate, 10);
353 fprintf(fp, "%-15s ", "");
354 format_rate(fp, vals, n->rate, 12);
355 format_rate(fp, vals, n->rate, 13);
356 format_rate(fp, vals, n->rate, 14);
357 format_rate(fp, vals, n->rate, 15);
360 fprintf(fp, "%-15s ", "");
361 format_rate(fp, vals, n->rate, 5);
362 format_rate(fp, vals, n->rate, 7);
363 format_rate(fp, vals, n->rate, 9);
364 format_rate(fp, vals, n->rate, 17);
367 fprintf(fp, "%-15s ", "");
368 format_rate(fp, vals, n->rate, 16);
369 format_rate(fp, vals, n->rate, 18);
370 format_rate(fp, vals, n->rate, 19);
371 format_rate(fp, vals, n->rate, 20);
377 void dump_kern_db(FILE *fp)
379 struct ifstat_ent *n;
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");
570 static const struct option longopts[] = {
571 { "help", 0, 0, 'h' },
572 { "ignore", 0, 0, 'a' },
573 { "scan", 1, 0, 'd'},
574 { "errors", 0, 0, 'e' },
575 { "nooutput", 0, 0, 'n' },
576 { "reset", 0, 0, 'r' },
577 { "noupdate", 0, 0, 's' },
578 { "interval", 1, 0, 't' },
579 { "version", 0, 0, 'V' },
580 { "zeros", 0, 0, 'z' },
584 int main(int argc, char *argv[])
587 struct sockaddr_un sun;
588 FILE *hist_fp = NULL;
592 while ((ch = getopt_long(argc, argv, "hvVzrnasd:t:eK",
593 longopts, NULL)) != EOF) {
614 scan_interval = atoi(optarg) * 1000;
615 if (scan_interval <= 0) {
616 fprintf(stderr, "ifstat: invalid scan interval\n");
621 time_constant = atoi(optarg);
622 if (time_constant <= 0) {
623 fprintf(stderr, "ifstat: invalid time constant divisor\n");
629 printf("ifstat utility, iproute2-ss%s\n", SNAPSHOT);
641 sun.sun_family = AF_UNIX;
643 sprintf(sun.sun_path+1, "ifstat%d", getuid());
645 if (scan_interval > 0) {
646 if (time_constant == 0)
648 time_constant *= 1000;
649 W = 1 - 1/exp(log(10)*(double)scan_interval/time_constant);
650 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
651 perror("ifstat: socket");
654 if (bind(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) < 0) {
655 perror("ifstat: bind");
658 if (listen(fd, 5) < 0) {
659 perror("ifstat: listen");
663 perror("ifstat: daemon");
666 signal(SIGPIPE, SIG_IGN);
667 signal(SIGCHLD, sigchild);
675 if (getenv("IFSTAT_HISTORY"))
676 snprintf(hist_name, sizeof(hist_name),
677 "%s", getenv("IFSTAT_HISTORY"));
679 snprintf(hist_name, sizeof(hist_name),
680 "%s/.ifstat.u%d", P_tmpdir, getuid());
685 if (!ignore_history || !no_update) {
688 fd = open(hist_name, O_RDWR|O_CREAT|O_NOFOLLOW, 0600);
690 perror("ifstat: open history file");
693 if ((hist_fp = fdopen(fd, "r+")) == NULL) {
694 perror("ifstat: fdopen history file");
697 if (flock(fileno(hist_fp), LOCK_EX)) {
698 perror("ifstat: flock history file");
701 if (fstat(fileno(hist_fp), &stb) != 0) {
702 perror("ifstat: fstat history file");
705 if (stb.st_nlink != 1 || stb.st_uid != getuid()) {
706 fprintf(stderr, "ifstat: something is so wrong with history file, that I prefer not to proceed.\n");
709 if (!ignore_history) {
712 if ((tfp = fopen("/proc/uptime", "r")) != NULL) {
713 if (fscanf(tfp, "%ld", &uptime) != 1)
717 if (uptime >= 0 && time(NULL) >= stb.st_mtime+uptime) {
718 fprintf(stderr, "ifstat: history is aged out, resetting\n");
719 ftruncate(fileno(hist_fp), 0);
723 load_raw_table(hist_fp);
729 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) >= 0 &&
730 (connect(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) == 0
731 || (strcpy(sun.sun_path+1, "ifstat0"),
732 connect(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) == 0))
733 && verify_forging(fd) == 0) {
734 FILE *sfp = fdopen(fd, "r");
736 if (hist_db && source_mismatch) {
737 fprintf(stderr, "ifstat: history is stale, ignoring it.\n");
744 if (hist_db && info_source[0] && strcmp(info_source, "kernel")) {
745 fprintf(stderr, "ifstat: history is stale, ignoring it.\n");
750 if (info_source[0] == 0)
751 strcpy(info_source, "kernel");
755 if (ignore_history || hist_db == NULL)
756 dump_kern_db(stdout);
758 dump_incr_db(stdout);
761 ftruncate(fileno(hist_fp), 0);
763 dump_raw_db(hist_fp, 1);