sbm

simple bandwidth monitor
git clone git://git.2f30.org/sbm
Log | Files | Refs | LICENSE

commit 01ac84da9cc200978838291fb449752318cfee96
parent d861a9cfef7ca732d6cc47fc79635508715f7bbb
Author: sin <sin@2f30.org>
Date:   Tue, 16 Feb 2016 16:02:00 +0000

Add Linux support

Diffstat:
Msbm.1 | 2+-
Msbm.c | 45++++++++++++++++++++++++++++++++++++++++-----
2 files changed, 41 insertions(+), 6 deletions(-)

diff --git a/sbm.1 b/sbm.1 @@ -9,7 +9,7 @@ .Op Fl i Ar interface .Sh DESCRIPTION .Nm -is a simple bandwidth monitor for BSD systems. +is a simple bandwidth monitor. .Sh OPTIONS .Bl -tag -width "-i interface" .It Fl i Ar interface diff --git a/sbm.c b/sbm.c @@ -15,11 +15,14 @@ */ #include <sys/socket.h> +#ifdef __linux__ +#include <linux/if_link.h> +#else #include <sys/sysctl.h> - -#include <net/if.h> #include <net/if_dl.h> #include <net/route.h> +#endif +#include <net/if.h> #include <err.h> #include <ifaddrs.h> @@ -38,7 +41,7 @@ scan(char *ifname) struct ifaddrs *ifas, *ifa; int found = 0; - if (getifaddrs(&ifas) == -1) + if (getifaddrs(&ifas) < 0) err(1, "getifaddrs"); if (*ifname) { for (ifa = ifas; ifa; ifa = ifa->ifa_next) { @@ -53,7 +56,8 @@ scan(char *ifname) continue; if (ifa->ifa_flags & IFF_RUNNING) { if (ifa->ifa_flags & IFF_UP) { - strlcpy(ifname, ifa->ifa_name, IFNAMSIZ); + strncpy(ifname, ifa->ifa_name, IFNAMSIZ); + ifname[IFNAMSIZ - 1] = '\0'; found = 1; break; } @@ -65,6 +69,35 @@ scan(char *ifname) errx(1, "no usable interface found"); } +#ifdef __linux__ +void +sample(char *ifname, unsigned long long *rxbytes, unsigned long long *txbytes, + unsigned long long *rxpps, unsigned long long *txpps) +{ + struct ifaddrs *ifas, *ifa; + struct rtnl_link_stats *stats = NULL; + + if (getifaddrs(&ifas) < 0) + err(1, "getifaddrs"); + for (ifa = ifas; ifa; ifa = ifa->ifa_next) { + if (strcmp(ifa->ifa_name, ifname)) + continue; + if (!ifa->ifa_data || !ifa->ifa_addr) + break; + if (ifa->ifa_addr->sa_family == AF_PACKET) { + stats = ifa->ifa_data; + *rxbytes = stats->rx_bytes; + *txbytes = stats->tx_bytes; + *rxpps = stats->rx_packets; + *txpps = stats->tx_packets; + break; + } + } + freeifaddrs(ifas); + if (!stats) + errx(1, "interface %s cannot be sampled", ifname); +} +#else void sample(char *ifname, unsigned long long *rxbytes, unsigned long long *txbytes, unsigned long long *rxpps, unsigned long long *txpps) @@ -110,6 +143,7 @@ sample(char *ifname, unsigned long long *rxbytes, unsigned long long *txbytes, if (!sdl) errx(1, "interface %s cannot be sampled", ifname); } +#endif void scale(char **suffix, unsigned long long *bits) @@ -176,7 +210,8 @@ main(int argc, char *argv[]) ARGBEGIN { case 'i': - strlcpy(ifname, EARGF(usage()), sizeof(ifname)); + strncpy(ifname, EARGF(usage()), sizeof(ifname)); + ifname[IFNAMSIZ - 1] = '\0'; break; default: usage();