Get the local MAC address in Linux

This code snippet shows how to get local MAC (hardware) address in Unix-like systems. But works in Windows too using Cygwin.

#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <sys/fcntl.h>
#include <sys/errno.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <stdio.h>
int main(int argc, char ** argv) {
  struct ifreq ifr;
  int s;
  if ((s = socket(AF_INET, SOCK_STREAM,0)) < 0) {
    return -1;
  strcpy(ifr.ifr_name, argv[1]);
  if (ioctl(s, SIOCGIFHWADDR, &ifr) < 0) {
    return -1;
  unsigned char *hwaddr = (unsigned char *)ifr.ifr_hwaddr.sa_data;
  printf("%02X:%02X:%02X:%02X:%02X:%02X\n", hwaddr[0], hwaddr[1], hwaddr[2],
                                          hwaddr[3], hwaddr[4], hwaddr[5]);
  return 0;