Home » C++ programs » C++ Most popular & searched programs

C++ program to set MAC address in Linux Devices

Learn: How to set MAC address (physical address) in Linux devices using C++ program, this program is compiled and executed in G++ compiler.

We have already discussed about MAC Address (Read: what is MAC address? And How to get MAC Address using C++ program), In this article we are going to learn how to set MAC Address using C++ program in Linux Devices?

Note: Since MAC address is assigned through manufacturer of the product, but if you are writing code for an embedded devices and needs to define it, this program will be helpful.

Points to remember while defining the MAC address:

  • Link down the network
  • Run command to set MAC address
  • And, link up the network

Consider the program:



#include <iostream>
using namespace std;

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void  setMac(char * mac)
{
	char cmd[64];
	//network interface
	char nwkInf[5]="eth0";

	memset(cmd,0X00,64);
	
	//command to link down network
	sprintf((char *)cmd,(const char *)"ip link set %s down",nwkInf);
	system((const char *)cmd); 
	usleep(500);
	
	memset(cmd,0X00,64);
	//command to set MAC address
	sprintf((char *)cmd,(const char *)"ifconfig %s hw ether %s",nwkInf,mac);
	system((const char *)cmd);
	usleep(500);

	memset(cmd,0X00,64);
	//command to link up network
	sprintf((char *)cmd,(const char *)"ip link set %s up",nwkInf);
	system((const char *)cmd);
	usleep(500);

}

int main()
{
    //funcion call to set MAC address
	setMac("67:45:C4:AC:2F:CA");
	return 0;
}

Here, "67:45:C4:AC:2F:CA" is MAC address to be assigned.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.