如何找到一个mac地址?

时间:2012-04-28 15:13:16

标签: c++ visual-c++

如何在c ++中找到当前运行应用程序的计算机的mac地址,然后将该mac地址与某个mac地址进行比较?

所以我们说要与之比较的某个mac地址是AB-12-CD-34-EF-56,如何找到运行该应用程序的mac地址,然后将该mac地址与{{1}进行比较} MAC地址?做这样的事情的最好和最简单的方法是什么?

1 个答案:

答案 0 :(得分:2)

在Windows上,您可以使用GetAdaptersAddresses()功能获取包含PhysicalAddress[MAX_ADAPTER_ADDRESS_LENGTH];的{​​{3}}结构(即mac地址)。

此函数将引入库Iphlpapi.lib和头文件<iphlpapi.h>作为依赖项。一个简单的例子,它将打印来自可用适配器的所有mac地址:

#include <Winsock2.h>
#include <iphlpapi.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <vector>
#pragma comment(lib, "IPHLPAPI.lib")

int main(int argc, char* argv[]){
  ULONG outBufLen = sizeof(IP_ADAPTER_ADDRESSES);
  GetAdaptersAddresses(0, 0, NULL, NULL, &outBufLen);
  std::vector<uint8_t> bytes(outBufLen, 0);
  PIP_ADAPTER_ADDRESSES pCurrAddresses = (IP_ADAPTER_ADDRESSES *)bytes.data();
  DWORD dwRetVal = GetAdaptersAddresses(0, 0, NULL, pCurrAddresses, &outBufLen);
  if (dwRetVal == NO_ERROR) {
    while (pCurrAddresses != NULL){ 
      for (size_t i = 0; i < (int) pCurrAddresses->PhysicalAddressLength; i++) {
        if (i == (pCurrAddresses->PhysicalAddressLength - 1))
          std::printf("%.2X\n", (int) pCurrAddresses->PhysicalAddress[i]);
        else
          std::printf("%.2X-",(int) pCurrAddresses->PhysicalAddress[i]);
      }
      pCurrAddresses = pCurrAddresses->Next;
    }
  }
  std::system("pause");
  return 0;
}