How to get MAC address of your machine using a C program?

David Murdoch picture David Murdoch · May 19, 2011 · Viewed 13.4k times · Source

This question is exactly like this question: How to get MAC address of your machine using a C program?

"I am working on Ubuntu. How can I get MAC address of my machine or an interface say eth0 using C program."


Now, I don't usually touch C...but in this case I have to. Since I don't really know what is going on in the following code, which was taken from the answer linked to above, I need some help.

#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <netdb.h>
#include <stdio.h>

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

  strcpy(s.ifr_name, "eth0");
  if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) {
    int i;
    for (i = 0; i < 6; ++i)
      printf(" %02x", (unsigned char) s.ifr_addr.sa_data[i]);
    puts("\n");
    return 0;
  }
  return 1;
}

Instead of a function that prints the MAC Address I need a function that returns it as a string. You know, like this:

const char * gettaStringFromNativeCode(void) 
{
    return "This is a string";
}

This is to be used with Mozilla Chromeless, which uses Firefox's new JCTYPES like this.

Basically, I'm looking to do something like this (borrowing from C#):

// Using "string" here because its pseudo-code and I don't know what i'm doing. :-)
string getMAC()
{
  struct ifreq s;
  int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);

  strcpy(s.ifr_name, "eth0");
  var macAddress = string.Empty; // yah, this is actually C#
  if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) {
    int i;
    for (i = 0; i < 6; ++i)
       // yah, this is a bit of C# too.
      macAddress += string.Format(" %02x", (unsigned char) s.ifr_addr.sa_data[i]) );
  }
  return macAddress;
}

Answer

Seth Robertson picture Seth Robertson · May 19, 2011
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <netdb.h>
#include <stdio.h>

char *getmac(char *iface)
{
#define MAC_STRING_LENGTH 13
  char *ret = malloc(MAC_STRING_LENGTH);
  struct ifreq s;
  int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);

  strcpy(s.ifr_name, iface);
  if (fd >= 0 && ret && 0 == ioctl(fd, SIOCGIFHWADDR, &s))
  {
    int i;
    for (i = 0; i < 6; ++i)
      snprintf(ret+i*2,MAC_STRING_LENGTH-i*2,"%02x",(unsigned char) s.ifr_addr.sa_data[i]);
  }
  else
  {
    perror("malloc/socket/ioctl failed");
    exit(1);
  }
  return(ret);
}

int main()
{
  char *mac = getmac("eth0");
  printf("%s\n",mac);
  free(mac);
}