A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

C++ program to get MAC address of Linux based network device
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)

Similar questions


need a help?


find thousands of online teachers now