Find a Network Interface Mac Address Programatically on Linux

Using the Mac Address of Network Interfaces in programs is a common requirement. The old age way of getting the mac address programatically on linux was to parse the not-so-machine-friendly ifconfig output. However with the sysfs file system mounted under /sys, accessing information from kernel sub-systems has become very easy.

e.g. The Mac Address of eth0 interface can be accessed by reading the /sys/class/net/eth0/address file.

Wlan0-Eth0-Address-Programatically-sysfs

The code below is an example of how to use parse this information from within a C program.

#include <stdio.h>
#include <string.h>
#include <stdint.h>

int mac_get_ascii_from_file(const char *filename, char *addr) {
  FILE *fp;
  int i = 0;
  char c;
  fp = fopen(filename, "r");
  if (fp != NULL) {
    while (!feof(fp)) {
      c = fgetc(fp);
      if (c == ':')
        continue;
      if (c == '\n')
        break;
      addr[i++] = c;
    }
  }
  fclose(fp);
  return 0;
}

int mac_get_binary_from_file(const char *filename, uint8_t * mac) {
  int status = 1;
  char buf[256];
  FILE *fp = fopen(filename, "rt");
  memset(buf, 0, 256);
  if (fp) {
    if (fgets(buf, sizeof buf, fp) > 0) {
      sscanf(buf, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &mac[0],
             &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);
      status = 0;
    }
    fclose(fp);
  }
  return status;
}

int main(void) {
  char macaddr[13];
  uint8_t mac[6];
  memset(macaddr, '\0', 13);
  mac_get_ascii_from_file("/sys/class/net/eth0/address", macaddr);
  printf("My Mac Address - %s\n", macaddr);
  mac_get_binary_from_file("/sys/class/net/eth0/address", mac);
  printf("My Mac Address - %hhx:%hhx:%hhx:%hhx:%hhx:%hhx\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  return 0;
}

The sample output of the above program is shown below.

Output-of-macaddr-program

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.