Monday, March 2, 2015

Explanation and code for reading interface names and MAC addresses

Here is a useful piece of user space code that can read the interfaces and their corresponding MAC addresses.

Download complete source here.
Complete repository can be downloaded or cloned here.

Main parts of the code:

The main parts of the program are:

1. Given the name of the interface, execute an IOCTL to get the hardware address:
/* gets the MAC addr for the interface */
int get_if_mac(char *eth, char *mac) {
    struct ifreq ifr;
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd == -1) return -1;
    strncpy(ifr.ifr_name, eth, sizeof(ifr.ifr_name));
    if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) return -1;
    memcpy(mac, ifr.ifr_hwaddr.sa_data, IFHWADDRLEN);
    return 0;

2. Get interface info from the system in a linkedlist ifaddr:
 if (getifaddrs(&ifaddr) == -1) {
3.  Loop and call the function get_if_mac() in step 1.

Sample output:

interface lo family AF_INET address MAC 00:00:00:00:00:00
interface eth0 family AF_INET address MAC XX:YY:zz:4b:46:75
interface lo family AF_INET6 address ::1 MAC 00:00:00:00:00:00
interface eth0 family AF_INET6 address xx80::yy51:zzff:qw4b:uu75%eth0 MAC XX:YY:ZZ:4b:46:75


Post a Comment