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";

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

	//command to link up network
	sprintf((char *)cmd,(const char *)"ip link set %s up",nwkInf);
	system((const char *)cmd);


int main()
    //funcion call to set MAC address
	return 0;

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

Related Programs


Comments and Discussions!

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.