Danny's Tech Musings



Find MAC/Network Hardware Address On Linux/Unix

The following piece of code will help you find the MAC(Media Access Control)/Hardware Address of your network card. An important point is that Linux sometimes sets up virtual addresses and these addresses are retrieved as well. You can also get the names of your network interfaces/cards on your system.




#include <sys/ioctl.h>
#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <cstdio>
using namespace std;

void getMAC( )
{
//Interface structure to pass commands to ioctl
struct ifreq ifr;


//Structure containing the network interface name and index
struct if_nameindex* if_name;

//Convenience variable to point to the MAC address
unsigned char* mac;

//String buffer to store the MAC
char actualMac[ 50 ];

int sd,
i = 0;

sd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
if(sd != -1)
{

//Retrieve the available list of network interface cards and their names and indices
if_name = if_nameindex();

//Parse the list
//The ending entry in if_name is terminated by NULL
while( if_name[i].if_name != NULL )

{
//Copy the interface name to the ioctl request structure
memcpy(&ifr.ifr_name, if_name[i].if_name, IFNAMSIZ);

//Pass signal to ioctl requesting the hardware address
if (ioctl(sd, SIOCGIFHWADDR, &ifr) >= 0)
{
//Assign result in MAC (because "mac" is shorter than "ifr.ifr_hwaddr.sa_data" :-D )
mac = (unsigned char*) &ifr.ifr_hwaddr.sa_data;

//Store the address as a string in "actualMac"

sprintf(actualMac,"%02X:%02X:%02X:%02X:%02X:%02X",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);

}
else //Error: Unable to retrieve the address
printf("Unable to retrieve MAC address for %s\n", if_name[i].if_name );


++i;
}

//Free the buffers used by the if_nameindex function
if_freenameindex(if_name);
}

}



0 comments

Make A Comment
top