// how to get a mac address

#include <stdio.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <string.h>

int getmac()
{
  // how to get a mac address

  // interface request struct
  struct ifreq ifr;

  // buffer for the mac address (48bits)
  unsigned char mac[6];
  memset(&mac,'\0',sizeof(mac));
  
  // return value
  int ret = -1;

  // socket for ioctl
  int fd = socket(AF_INET,SOCK_DGRAM,0);
  if( fd < 0 ) return -1; // error

  // copy name of interface into ifr.ifr_name, e.g.
  strcpy(ifr.ifr_name,"lo");
  strcpy(ifr.ifr_name,"enp2s0");

  // ioctl SIOCGIFHWADDR
  ret = ioctl(fd,SIOCGIFHWADDR, &ifr);

  // ret should be 0
  if( ret ) return ret; // error

  // copy the data
  memcpy(mac,ifr.ifr_hwaddr.sa_data, 6);

  // print out the mac
  for( int i=0; i<6; i++ ) {
    printf("%02x%c",mac[i],i==5?'\n':':');
  }

clean_up:
  close(fd);

  return 0;
}

int main()
{
  getmac();
}