Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the same MAC address?

Tags:

c++

c

winapi

I am using the following code to get the MAC address:

IP_ADAPTER_INFO adpInfo[16];
DWORD len = sizeof(adpInfo);
GetAdaptersInfo(adpInfo, &len );
printf("%02x%02x%02x%02x%02x%02x", adpInfo[0].Address[0], adpInfo[0].Address[1], adpInfo[0].Address[2], adpInfo[0].Address[3], adpInfo[0].Address[4], adpInfo[0].Address[5]);

However, if the computer has many network adapters (for example: Ethernet and WiFi), then every time I call this code I get a different MAC address.

Is there a way to always get the same MAC address (for example: Ethernet).

like image 452
John Avatar asked Sep 29 '22 00:09

John


1 Answers

Since GetAdaptersInfo method includes almost as much information as IPCONFIG /ALL (including your DHCP server, Gateway, IP address list, subnet mask and WINS server) you can use that. It also enumerates all the NICs on your PC, even if they are not connected to valid networks (but the NICs do have to be "enabled" in Windows)

Sample, print all interfaces:

static void GetMACaddress(void)
{
  IP_ADAPTER_INFO AdapterInfo[16];

  DWORD dwBufLen = sizeof(AdapterInfo);

  DWORD dwStatus = GetAdaptersInfo(AdapterInfo, &dwBufLen);

  assert(dwStatus == ERROR_SUCCESS);

  PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;

  do {
    PrintMACaddress(pAdapterInfo->Address);
    pAdapterInfo = pAdapterInfo->Next;
  }
  while(pAdapterInfo);
}

You can save the AdapterName, then compare it in next calls to make sure the MAC of specified adapter is retrieved.

Look at here for IP_ADAPTER_INFO structure: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366062%28v=vs.85%29.aspx

Code from: http://www.codeguru.com/cpp/i-n/network/networkinformation/article.php/c5451/Three-ways-to-get-your-MAC-address.htm

like image 142
Ciro Pedrini Avatar answered Nov 26 '22 05:11

Ciro Pedrini