#include <stdio.h>
#include <netlink/route/link.h>

struct nl_cache *link_cache;
struct nl_sock *sock;
struct rtnl_link *link;


unsigned int get_rx_bytes(const char *interface_name) {
    // load all link data into cache
    if (rtnl_link_alloc_cache(sock, AF_UNSPEC, &link_cache) < 0) {
        nl_socket_free(sock);
        return -1;
        }

    // filter link by name
    if ((link = rtnl_link_get_by_name(link_cache, interface_name)) == NULL) {
        printf("unknown interface/link name.\n");
        return -1;
        }
        
    // read and return counter
    return rtnl_link_get_stat(link, RTNL_LINK_RX_BYTES);
    }


int main(int argc, char *argv[]) {
    // initialize netlink socket
    sock = nl_socket_alloc();
    if (nl_connect(sock, NETLINK_ROUTE) < 0) {
        perror("nl_connect error:");
        return 1;
        }
    
    // update, print, sleep, update, print    
    printf("rx_bytes: %u\n", get_rx_bytes("eth0"));
    sleep(1);
    printf("rx_bytes: %u\n", get_rx_bytes("eth0"));
    }

