#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if.h>
#include <net/if_var.h>
#include <net/if_dl.h>
#include <net/if_types.h>
#include <net/if_mib.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/in_var.h>
#include <unistd.h>
static u_int64_t opackets = 0;
static u_int64_t ipackets = 0;
static u_int64_t obytes = 0;
static u_int64_t ibytes = 0;
int get_stats(char *interface)
{
int ret = 0;
char name[32];
int mib[6];
char *buf = NULL, *lim, *next;
size_t len;
struct if_msghdr *ifm;
unsigned int ifindex = 0;
if (interface != 0)
ifindex = if_nametoindex(interface);
mib[0] = CTL_NET;
mib[1] = PF_ROUTE;
mib[2] = 0;
mib[3] = 0;
mib[4] = NET_RT_IFLIST2;
mib[5] = 0;
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0)
return ret;
if ((buf = malloc(len)) == NULL)
{
printf("malloc failed\n");
exit(1);
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0)
{
if (buf)
free(buf);
return ret;
}
lim = buf + len;
for (next = buf; next < lim;)
{
ifm = (struct if_msghdr *)next;
next += ifm->ifm_msglen;
if (ifm->ifm_type == RTM_IFINFO2)
{
struct if_msghdr2 *if2m = (struct if_msghdr2 *)ifm;
struct sockaddr_dl *sdl = (struct sockaddr_dl *)(if2m + 1);
strncpy(name, sdl->sdl_data, sdl->sdl_nlen);
name[sdl->sdl_nlen] = 0;
if (interface != 0 && if2m->ifm_index != ifindex)
continue;
/* Get the interface stats. These may get overriden below on a
* per-interface basis. */
opackets = if2m->ifm_data.ifi_opackets;
ipackets = if2m->ifm_data.ifi_ipackets;
obytes = if2m->ifm_data.ifi_obytes;
ibytes = if2m->ifm_data.ifi_ibytes;
if (ret == 0)
{
printf("%-5.5s %8.8s %10.10s ",
"Name", "Ipkts", "IBytes");
printf("%8.8s %10.10s\n", "Opkts", "Obytes");
ret = 1;
}
printf("%-5.5s %-8.8llu ", name, ipackets);
printf("%10.10llu ", ibytes);
printf("%-8.8llu ", opackets);
printf("%10.10llu\n", obytes);
}
}
free(buf);
return ret;
}
int main(int argc, char *argv[])
{
char *ifname;
int r;
int sleeptime = 2;
if (argc > 1)
{
ifname = argv[1];
}
else
{
ifname = NULL;
}
r = get_stats(ifname);
if (r)
{
u_int64_t ib = ibytes;
u_int64_t ob = obytes;
sleep(sleeptime);
get_stats(ifname);
printf("%llu %llu\n", (ibytes - ib) / sleeptime, (obytes - ob) / sleeptime);
}
else
{
printf("No interface %s\n", ifname);
}
}