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

Learn: How to get/display MAC address of a Linux based network devices using C++ program? This program is compiled and executed in G++ compiler.
[Last updated : February 26, 2023]

Getting the MAC address of Linux based network device using C++ Program

We have already discussed about MAC address or physical address of a network device (Read: What is MAC address?), here we are going to learn how we can get the MAC address of any Linux based network device by executing Linux commands?

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

#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.



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.