MAC address with getifaddrs

shaggy picture shaggy · Jul 20, 2011 · Viewed 27.9k times · Source

Is there a way to get interface's MAC address via getifaddrs() ?

I already have this, to get IP addresses, but I have kinda missed MAC. Ive tried to look for the information in getifaddrs(), but there is nothing about MAC addresses

struct ifaddrs *iflist, *iface;

  if (getifaddrs(&iflist) < 0) 
  {
      perror("getifaddrs");
  }

  char addrp[INET6_ADDRSTRLEN];
  char macp[INET6_ADDRSTRLEN];
  int i=0;

  for (iface = iflist; iface; iface = iface->ifa_next) 
  {
    int af = iface->ifa_addr->sa_family;
    const void *addr;
    const void *mac;

      switch (af) 
      {
        case AF_INET:
          addr = &((struct sockaddr_in *)iface->ifa_addr)->sin_addr;
          break;
      //get mac address somehow?
        default:
          addr = NULL;
      }

      if (addr) 
      {
        if (inet_ntop(af, addr, addrp, sizeof addrp) == NULL)
        {
           perror("inet_ntop");
           continue;
        }
    if (inet_ntop(af, mac, macp, sizeof macp) == NULL) // this is already for MAC add
        {
           perror("inet_ntop");
           continue;
        }
    if (strcmp(addrp, "127.0.0.1") != 0) 
    {
       strcat(tableO[i].IPaddr, addrp);
       strcat(tableO[i].MACaddr, macp);
       i++;
    }
      }

Thanks

Answer

Giampaolo Rodol&#224; picture Giampaolo Rodolà · Sep 25, 2014

getifaddrs() already provides the MAC address associated with each interface. On Linux, when you bump into a family == AF_PACKET that is the MAC address. Same thing on OSX / BSD but in that case the family will be AF_LINK.