get the IFLA_STATS attribute (rx/tx byte counters) for a specific interface

Thomas Graf tgraf at infradead.org
Thu Mar 3 10:48:56 EST 2011


On Thu, Mar 03, 2011 at 04:13:11PM +0100, Jan-Philip gehrcke wrote:
> 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);
>     }

Do rtnl_link_alloc_cache() once and only nl_cache_resync() for ever iteration.
You are currently leaking the whole cache in every iteration.

This can be done faster by using the lower level APIs and by parsing the
link message replies yourself. I am not sure why you want to optimize this
though.



More information about the libnl mailing list