I would like to write a piece of code which checks, for each network device (e.g. eth0, lo, master devices) some statistics and configuration data about that device.
I could find the statistics data (and most of the configuration data) in /sys/class/net/..., however, I couldn't find any C/C++ API or any entry in procfs/sysfs listing the inet addr, netmask and gateway.
Some alternatives I checked:
- parsing the output from ifconfig/route/some other utilities: I don't want to start a subprocess every time I need to do the inspection.
- parsing /etc/sysconfig/network-scripts/: will give me only the start-up configuration, and not the current state.
Also, since this code is intended for a product in my workplace, where every external library is inspected thoroughly (meaning it will take me forever to add any external library) I prefer solutions which rely on Linux native API and not external libraries.
Thanks!
Running netstat through strace (on a random Linux box), reveals the following sequence of calls taking place:
So, the "secret" seems to be to create a socket, then do a bunch of
ioctl()
calls to access the current information.Take a look at
/usr/include/ifaddrs.h
. There is a GNU specific API for this.There sure is using a struct of ifreq and ioctl() calls you can grab all interface information:
Man page is here Ifreq manpage
Quick edit, this function requires that the interface has been assigned before it is called, like so:
Ensuring you have allocated the memory first, then call like so