The C interface is called ifaddrs, you may include it with:
#include <sys/types.h>
#include <ifaddrs.h>
The functions you are interested in are getifaddrs
and once done with the data, freeifaddrs
.
struct ifaddrs {
struct ifaddrs *ifa_next; /* Next item in list */
char *ifa_name; /* Name of interface */
unsigned int ifa_flags; /* Flags from SIOCGIFFLAGS */
struct sockaddr *ifa_addr; /* Address of interface */
struct sockaddr *ifa_netmask; /* Netmask of interface */
union {
struct sockaddr *ifu_broadaddr;
/* Broadcast address of interface */
struct sockaddr *ifu_dstaddr;
/* Point-to-point destination address */
} ifa_ifu;
#define ifa_broadaddr ifa_ifu.ifu_broadaddr
#define ifa_dstaddr ifa_ifu.ifu_dstaddr
void *ifa_data; /* Address-specific data */
};
This structure includes all the info as the ifconfig
command line tool returns.
For C++ users, I suggest you use a deleter like this:
void ifaddrs_deleter(struct ifaddrs * ia)
{
freeifaddrs(ia);
}
And attach the result of getifaddrs()
to it with:
struct ifaddrs * ifa_start(nullptr);
if(getifaddrs(&ifa_start) != 0)
{
return;
}
// will automatically delete on exception or any return
std::shared_ptr<struct ifaddrs> auto_free(ifa_start, ifaddrs_deleter);