|
C code to find out network interfaces and mac address in Redhat Linux |
Saturday, January 15, 2005 |
i needed mac address of network interface in linux for my program. Many people advised me to look into the code of ifconfig. But is is very vast i was finding spme small function that will do my work. Previously I was reading some files in /proc file system to get this id, but in Redhat linux 9.0 I was not able to find the interface file. So I searched the internet and here is the code
#include
#include
//#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
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:%02Xn", mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
++i;
}
/* free memory allocated by if_nameindex() */
if_freenameindex(if_name);
return 0;
}
|
posted by Sameer @ 4:50 AM |
|
|
|
|