Obtaining information about network interfaces is an important aspect of network programming and administration. On the Linux operating system, network interfaces are managed by the kernel and can be enumerated using a variety of tools and techniques. This tutorial explains how to get all network interfaces on Linux using C++.
To enumerate all network interfaces on Linux using C++, we can use the getifaddrs
function. It retrieves a linked list of interface addresses, which we can use to obtain information about each interface.
In the following code, we loop over the list to obtain information about each interface. The AF_PACKET
is used to filter out only network interfaces that are of the packet-oriented type. It is a type of network interface that allows access to raw network frames and can be used for low-level network programming. Finally, the name of each interface is obtained by using the ifa_name
field, which is printed to the console.
After we are done using the linked list, we need to free it using the freeifaddrs
function.
#include <iostream>
#include <ifaddrs.h>
int main()
{
struct ifaddrs *addrs;
getifaddrs(&addrs);
for (struct ifaddrs *addr = addrs; addr != nullptr; addr = addr->ifa_next) {
if (addr->ifa_addr && addr->ifa_addr->sa_family == AF_PACKET) {
std::cout << addr->ifa_name << std::endl;
}
}
freeifaddrs(addrs);
return 0;
}
Here is an example of the output you might see when running the code:
lo
enp3s0
wlo1
In this example, there are three network interfaces: lo
(loopback), enp3s0
(Ethernet), and wlo1
(wireless).
Leave a Comment
Cancel reply