C/C++

How to find MAC address of a linux network interface using SIOCGIFHWADDR ioctl

The following C programming example retrieves all network interfaces in a Linux system and their IP addresses and MAC addresses. The name of network interface and IP address are retrieved using SIOCGIFCONF ioctl while the hardware address of each individual interface is found using SIOCGIFHWADDR ioctl.

/* iflist.c */
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>

int get_iface_list(struct ifconf *ifconf)
{
  int sock, rval;

  sock = socket(AF_INET,SOCK_DGRAM,0);
  if(sock < 0)
  {
    perror("socket");
    return (-1);
  }

  if((rval = ioctl(sock, SIOCGIFCONF , (char*) ifconf  )) < 0 )
  perror("ioctl(SIOGIFCONF)");

  close(sock);

  return rval; More >