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, NULL, 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, *h;
384 for (n=kern_db; n; n=n->next) {
387 print_one_if(fp, n, n->val);
392 void dump_incr_db(FILE *fp)
394 struct ifstat_ent *n, *h;
399 for (n=kern_db; n; n=n->next) {
401 unsigned long long vals[MAXS];
402 struct ifstat_ent *h1;
404 memcpy(vals, n->val, sizeof(vals));
406 for (h1 = h; h1; h1 = h1->next) {
407 if (h1->ifindex == n->ifindex) {
408 for (i = 0; i < MAXS; i++)
409 vals[i] -= h1->val[i];
416 print_one_if(fp, n, vals);
423 void sigchild(int signo)
427 void update_db(int interval)
429 struct ifstat_ent *n, *h;
439 for (n = kern_db; n; n = n->next) {
440 struct ifstat_ent *h1;
441 for (h1 = h; h1; h1 = h1->next) {
442 if (h1->ifindex == n->ifindex) {
444 for (i = 0; i < MAXS; i++) {
445 if ((long)(h1->ival[i] - n->ival[i]) < 0) {
446 memset(n->ival, 0, sizeof(n->ival));
450 for (i = 0; i < MAXS; i++) {
452 unsigned long incr = h1->ival[i] - n->ival[i];
454 n->ival[i] = h1->ival[i];
455 sample = (double)(incr*1000)/interval;
456 if (interval >= scan_interval) {
457 n->rate[i] += W*(sample-n->rate[i]);
458 } else if (interval >= 1000) {
459 if (interval >= time_constant) {
462 double w = W*(double)interval/scan_interval;
463 n->rate[i] += w*(sample-n->rate[i]);
469 struct ifstat_ent *tmp = h;
483 #define T_DIFF(a,b) (((a).tv_sec-(b).tv_sec)*1000 + ((a).tv_usec-(b).tv_usec)/1000)
486 void server_loop(int fd)
488 struct timeval snaptime = { 0 };
491 p.events = p.revents = POLLIN;
493 sprintf(info_source, "%d.%lu sampling_interval=%d time_const=%d",
494 getpid(), (unsigned long)random(), scan_interval/1000, time_constant/1000);
503 gettimeofday(&now, NULL);
504 tdiff = T_DIFF(now, snaptime);
505 if (tdiff >= scan_interval) {
511 if (poll(&p, 1, tdiff + scan_interval) > 0
512 && (p.revents&POLLIN)) {
513 int clnt = accept(fd, NULL, NULL);
518 } else if ((pid = fork()) != 0) {
523 FILE *fp = fdopen(clnt, "w");
533 while (children && waitpid(-1, &status, WNOHANG) > 0)
538 int verify_forging(int fd)
541 socklen_t olen = sizeof(cred);
543 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, (void*)&cred, &olen) ||
546 if (cred.uid == getuid() || cred.uid == 0)
551 static void usage(void) __attribute__((noreturn));
553 static void usage(void)
556 "Usage: ifstat [OPTION] [ PATTERN [ PATTERN ] ]\n"
557 " -h, --help this message\n"
558 " -a, --ignore ignore history\n"
559 " -d, --scan=SECS sample every statistics every SECS\n"
560 " -e, --errors show errors\n"
561 " -n, --nooutput do history only\n"
562 " -r, --reset reset history\n"
563 " -s, --noupdate don;t update history\n"
564 " -t, --interval=SECS report average over the last SECS\n"
565 " -V, --version output version information\n"
566 " -z, --zeros show entries with zero activity\n");
571 static const struct option longopts[] = {
572 { "help", 0, 0, 'h' },
573 { "ignore", 0, 0, 'a' },
574 { "scan", 1, 0, 'd'},
575 { "errors", 0, 0, 'e' },
576 { "nooutput", 0, 0, 'n' },
577 { "reset", 0, 0, 'r' },
578 { "noupdate", 0, 0, 's' },
579 { "interval", 1, 0, 't' },
580 { "version", 0, 0, 'V' },
581 { "zeros", 0, 0, 'z' },
585 int main(int argc, char *argv[])
588 struct sockaddr_un sun;
589 FILE *hist_fp = NULL;
593 while ((ch = getopt_long(argc, argv, "hvVzrnasd:t:eK",
594 longopts, NULL)) != EOF) {
615 scan_interval = atoi(optarg) * 1000;
616 if (scan_interval <= 0) {
617 fprintf(stderr, "ifstat: invalid scan interval\n");
622 time_constant = atoi(optarg);
623 if (time_constant <= 0) {
624 fprintf(stderr, "ifstat: invalid time constant divisor\n");
630 printf("ifstat utility, iproute2-ss%s\n", SNAPSHOT);
642 sun.sun_family = AF_UNIX;
644 sprintf(sun.sun_path+1, "ifstat%d", getuid());
646 if (scan_interval > 0) {
647 if (time_constant == 0)
649 time_constant *= 1000;
650 W = 1 - 1/exp(log(10)*(double)scan_interval/time_constant);
651 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
652 perror("ifstat: socket");
655 if (bind(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) < 0) {
656 perror("ifstat: bind");
659 if (listen(fd, 5) < 0) {
660 perror("ifstat: listen");
664 perror("ifstat: daemon");
667 signal(SIGPIPE, SIG_IGN);
668 signal(SIGCHLD, sigchild);
676 if (getenv("IFSTAT_HISTORY"))
677 snprintf(hist_name, sizeof(hist_name),
678 "%s", getenv("IFSTAT_HISTORY"));
680 snprintf(hist_name, sizeof(hist_name),
681 "%s/.ifstat.u%d", P_tmpdir, getuid());
686 if (!ignore_history || !no_update) {
689 fd = open(hist_name, O_RDWR|O_CREAT|O_NOFOLLOW, 0600);
691 perror("ifstat: open history file");
694 if ((hist_fp = fdopen(fd, "r+")) == NULL) {
695 perror("ifstat: fdopen history file");
698 if (flock(fileno(hist_fp), LOCK_EX)) {
699 perror("ifstat: flock history file");
702 if (fstat(fileno(hist_fp), &stb) != 0) {
703 perror("ifstat: fstat history file");
706 if (stb.st_nlink != 1 || stb.st_uid != getuid()) {
707 fprintf(stderr, "ifstat: something is so wrong with history file, that I prefer not to proceed.\n");
710 if (!ignore_history) {
713 if ((tfp = fopen("/proc/uptime", "r")) != NULL) {
714 if (fscanf(tfp, "%ld", &uptime) != 1)
718 if (uptime >= 0 && time(NULL) >= stb.st_mtime+uptime) {
719 fprintf(stderr, "ifstat: history is aged out, resetting\n");
720 ftruncate(fileno(hist_fp), 0);
724 load_raw_table(hist_fp);
730 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) >= 0 &&
731 (connect(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) == 0
732 || (strcpy(sun.sun_path+1, "ifstat0"),
733 connect(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) == 0))
734 && verify_forging(fd) == 0) {
735 FILE *sfp = fdopen(fd, "r");
737 if (hist_db && source_mismatch) {
738 fprintf(stderr, "ifstat: history is stale, ignoring it.\n");
745 if (hist_db && info_source[0] && strcmp(info_source, "kernel")) {
746 fprintf(stderr, "ifstat: history is stale, ignoring it.\n");
751 if (info_source[0] == 0)
752 strcpy(info_source, "kernel");
756 if (ignore_history || hist_db == NULL)
757 dump_kern_db(stdout);
759 dump_incr_db(stdout);
762 ftruncate(fileno(hist_fp), 0);
764 dump_raw_db(hist_fp, 1);