Chapter 10. Network interfaces


Network interface addresses
#include <x/netif.H>

std::vector<x::netif> interfaces=x::netif::base::enumerate();

for (auto &netif_ref : interfaces)
   std::cout << "interface: " << netif_ref->getName() << std::endl;

   // ...

x::netif::base::enumerate() returns a vector of references to x::netifObj objects. This object holds metadata about one network interface. getName() returns the network interface's name. getIndex() and getFlags() return the corresponding interface metadata from the ioctl(2), calls that retrieve the network interface's index and flags (such as IFF_LOOPBACK).

std::vector<unsigned char> mac=netif_ref->getMacAddress(mac);

getMacAddress() returns a vector with the network interface's MAC address. The vector will be empty if the network interface's MAC address cannot be determined.

Network interface addresses

getAddrs() returns a reference to a constant vector of x::netif::ifaddr objects:

std::cout << "addresses: ";

const char *sep="";

for (auto &netif : netif_ref->getAddrs())
    std::cout << sep << (std::string)*netif.addr;

    if (netif.netmask->size())
        std::cout << "/" << (std::string)*netif.netmask;
    sep=", ";

std::cout << std::endl;

getAddrs() returns a native reference to a vector of x::netif::ifaddrs. A x::netif::ifaddr contains two x::const_sockaddrs: addr and netmask, the network interface's IP address and netmask. x::sockaddr is a reference to a reference-counted subclass of a std::vector<char> that holds a socket addressed subject. The netmask vector may be empty, if the no netmask is defined (the network interface is a point-to-point link).


x::netif::enumerate() enumerates a network interface only if it has at least one network address. A network interface without a defined address does not get enumerated.

The vector returned by getAddrs() will have more than one address if the network interface is multihomed.