Q:

C++ program to get MAC address of Linux based network device

0

C++ program to get MAC address of Linux based network device

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the program:

#include <iostream>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <net/if.h>
#include <unistd.h>

using namespace std;




void getMacAddress(char * uc_Mac)
{
   	 int fd;
	
	struct ifreq ifr;
	char *iface = "eth0";
	char *mac;
	
	fd = socket(AF_INET, SOCK_DGRAM, 0);

	ifr.ifr_addr.sa_family = AF_INET;
	strncpy((char *)ifr.ifr_name , (const char *)iface , IFNAMSIZ-1);

	ioctl(fd, SIOCGIFHWADDR, &ifr);

	close(fd);
	
	mac = (char *)ifr.ifr_hwaddr.sa_data;
	
	//display mac address
	sprintf((char *)uc_Mac,(const char *)"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
	
}

int main()
{
	char mac[32]={0};

	getMacAddress (mac);

	cout<<endl<<"Mac Address : "<<mac;
	return 0;
}

Output

Mac Address:  78:5A:C8:CF:2F:AF

To get MAC address we need to use some socket related stuffs, also need to use ioctl commands. First we open file descriptor and select network family (AF_NET) in case of IPv6 we use AF_NET6. Then get the data from socket and using sprintf save mac address into buffer.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Most popular and Searched C++ solved programs with Explanation and Output

Similar questions


need a help?


find thousands of online teachers now
C++ program to set MAC address in Linux Devices... >>
<< C++ program to set IP address, subnet mask, networ...