How to get MAC address of a device in C++?

This tutorial demonstrates How to get MAC address of a device in C++. We are going to learn what is MAC? What are its usage and how to obtain it from the system?

What is MAC

Media Access Control is full form of MAC. A MAC address is a hardware identification number that is used to uniquely identifies each device on a network. Manufactures give every network card, such as an Ethernet card or Wi-Fi card a number to identify it uniquely. Therefore it is permanent. This address plays very important roles in networking.

To get the MAC address in windows machine.

  1. Open CMD.
  2. Enter command “getmac“.
  3. Press enter and the result will show the address.

How to get MAC address of a device using C++

We are going to use “system()” function. This function allows us to execute any command from a c++ program.
Firstly, we will execute the “getmac” command through the program using system function. Then save the output in txt file. Secondly, we will open the file and print the data in it.

Demonstration:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <iterator>

using namespace std;

int main(){
  string cmd = "getmac";
  string filename = "macaddress.txt";
  
  system((cmd + ">" + filename).c_str());
  string line;
  ifstream myfile ("macaddress.txt");
  
  if(myfile.is_open()){
    while(getline(myfile,line)){
      cout<<line<<endl;
    }
    myfile.close();
  }
  else
  cout<<"Unable to open the file";
}

Explanation:

In the above code, we will use the system() function to execute the command. It is already saved in cmd string inside the main function. The filename can be anything a user wants. It is the name of the file which will contain the output of the command. Once the system command is executed the output will be saved inside the file. Now we will open the file using ifstream. Then print the whole data that is inside the file.

The benefit of using this method is that you can now use the exact method to execute many more commands.

For Practice:

Try using these commands and check what the output is:

  • ipconfig
  • whoami

Also Check these:

Leave a Reply

Your email address will not be published. Required fields are marked *