×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object 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.
[Last updated : February 26, 2023]

Setting the MAC address in Linux Devices using C++ Program

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

C++ code to set the MAC address in Linux Devices

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

Related Programs

Comments and Discussions!

Load comments ↻





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