Get MAC Address on Linux using C++

Get MAC Address on Linux using C++

A MAC (Media Access Control) address is a unique value assigned to a network interface card (NIC, also called network adapter) by the manufacturer to uniquely identify it. Getting the MAC address of a network interface is useful in many situations, especially in network administration, security, diagnostics and device identification. This tutorial explains how to get the MAC address on Linux using C++.

We can use the ioctl function with the SIOCGIFHWADDR request to retrieve the MAC address for a specified network interface on Linux.

In the following code, we create a socket, initialize an ifreq structure with the name of the interface (wlo1 in this case), and call the ioctl function. The MAC address is returned to the ifr_hwaddr member of the ifreq structure. Using the ether_ntoa function, we convert the binary MAC address to a human-readable string. Note that we create a character array with a size of 18 (17 characters for the MAC address string, plus a null terminator). Finally, we print MAC address to the console.

#include <sys/ioctl.h>
#include <linux/if.h>
#include <netinet/ether.h>
#include <unistd.h>
#include <netdb.h>
#include <cstring>
#include <iostream>

int main()
{
    int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);

    struct ifreq ifr{};
    strcpy(ifr.ifr_name, "wlo1");
    ioctl(fd, SIOCGIFHWADDR, &ifr);
    close(fd);

    char mac[18];
    strcpy(mac, ether_ntoa((ether_addr *) ifr.ifr_hwaddr.sa_data));

    std::cout << mac << std::endl;

    return 0;
}

Here's an example output of the program:

88:d8:2e:12:5a:d9

Leave a Comment

Cancel reply

Your email address will not be published.