Get NIC stats using ethtool in Rust

254 Views Asked by At

I'm trying to fetch the stats of a NIC device in Rust, which is basically the equivalent of running ethtool -S eth0.

I have been looking at the netlink interface for ethtool documentation and the existing libraries: neli and ethtool.

However, neither of them provide an out-of-box solution. This was my attempt as using the neli library: ethtool.rs. However, I keep getting device not found or operation not supported error. While for the ethtool library, I need to add the functionality in the library itself which I am currently trying to do.

Any help would be really appreciated as to what is the most straightforward way to do so without obviously running the system commands and reading the stdout.

2

There are 2 best solutions below

0
On BEST ANSWER

I ended up using ioctl to do the above instead of going through the hassle of creating the right netlink nested attributes.

Here's the code snippet for the same: ethtool.rs.

Much more straightforward, however obviously I'd be missing on some of the advantages of using netlink. But maybe that'd be a task for some other day.

0
On

If you want to go low-level, you could ask directly on the MDIO bus for link- and autoneg status. Will only work for Ethernet. Basically reimplement mii-tool.c (from the net-tools package).

You could also snoop around in the /sys/ filesystem for useful files to read. For example I've found /sys/devices/pci0000:00/.../net/enp5s0/carrier, which is a file you can open, and read() will return either "0\n" or "1\n".

Or for tx/rx stats, you could parse the (ascii) output of /proc/net/dev. Reading a device-file, even with two pointless ascii conversion, will be more performant than spawning a new process. There probably is some IOCTL for what you want, but the text files are so easy find and check.

Another (higher-level) option may be to listen for networkmanager events somehow, probably with a dbus client.