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;
}
int get_mac(char *name, unsigned char *mac)
{
struct ifreq ifr;
int sock, rval;
sock = socket(AF_INET,SOCK_DGRAM,0);
if(sock < 0)
{
perror("socket");
return (-1);
}
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name, name, IFNAMSIZ-1);
if((rval = ioctl(sock, SIOCGIFHWADDR, &ifr)) == 0) {
memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
}
close(sock);
return rval;
}
#define MACFMT "%02X:%02X:%02X:%02X:%02X:%02X"
#define MACBYTES(p) p[0],p[1],p[2],p[3],p[4],p[5]
int main()
{
static struct ifreq ifreqs[20];
struct ifconf ifconf;
struct sockaddr_in *sa;
int nifaces, i;
unsigned char mac[6];
memset(&ifconf,0,sizeof(ifconf));
ifconf.ifc_buf = (char*) (ifreqs);
ifconf.ifc_len = sizeof(ifreqs);
if(get_iface_list(&ifconf) < 0) return -1;
nifaces = ifconf.ifc_len/sizeof(struct ifreq);
printf("Interfaces (count = %d)\n", nifaces);
for(i = 0; i < nifaces; i++)
{
get_mac(ifreqs[i].ifr_name, mac);
sa = (struct sockaddr_in *) &ifreqs[i].ifr_addr;
printf("\t%-10s\t%s\t" MACFMT "\n", ifreqs[i].ifr_name,inet_ntoa(sa->sin_addr),MACBYTES(mac));
}
}
Output of the program:
[neo@techpulp ~]# gcc iflist.c -o ./iflist
[neo@techpulp ~]# ./iflist Interfaces (count = 3) lo 127.0.0.1 00:00:00:00:00:00 eth0 215.36.166.124 03:D6:3A:42:C9:B8 virbr0 192.168.198.1 71:C2:40:14:83:5D [neo@techpulp ~]#
This example assumes that all interfaces in the system have just one IPv4 address.


about 1 year ago
Hey, killer job on that one you guys!