4

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

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

4

1 回答 1

3

在 Windows 上,您可以使用该函数GetAdaptersAddresses()来获取IP_ADAPTER_ADDRESSES包含PhysicalAddress[MAX_ADAPTER_ADDRESS_LENGTH];(即 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;
}
于 2014-07-08T15:01:50.137 回答