Get an interface’s information

Here is a bit of code to get an interface’s information; including the interface name, and MAC address:


#include
#include
#include /* provides ifreq and IFNAMSIZ and if_nameindex */
#include /* provides IPPROTO_IP */
#include
#include
#include
#include

using namespace std;

void get_if_info()
{
struct ifreq ifr;
struct if_nameindex* if_name;
unsigned char* mac;
int sd;
int i = 0;

/* get socket descriptor */
sd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
if(sd == -1)
{ cerr << "Socket Error" << endl; exit(1);}

/* get all network interface names */
if_name = if_nameindex();

while( (if_name[i].if_index != 0) && (if_name[i].if_name != NULL) )
{
/* write the name of the interface to the ifreq struct */
memcpy(&ifr.ifr_name, if_name[i].if_name, IFNAMSIZ);

/* get hardware address */
if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
{ cerr << "ioctl Error: SIOCGIFHWADDR" << endl; exit(1); }

mac = (unsigned char*) &ifr.ifr_hwaddr.sa_data;

cout << if_name[i].if_name << endl;

/* display MAC */
printf("%02X:%02X:%02X:%02X:%02X:%02X\n", mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);

++i;
}
/* free memory allocated by if_nameindex() */
if_freenameindex(if_name);
}

This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>