c++ - 如何使用 C++ 在 Windows 中获取 MAC 地址?

标签 c++ windows mac-address

我需要一些有关 MAC 地址的帮助。我必须通过在 C++ 中使用一些代码来获得它,所以有人可以帮助我吗?我已经尝试了很多无用的代码。如果存在我应该研究查找 MAC 地址的任何特定方法或库,如果有人通过我的链接或其他内容了解更多信息,我将非常高兴。

最佳答案

我明白了!我和工作中的一个人使用以下代码解决了这个问题:

#include <stdio.h>
#include <Windows.h>
#include <Iphlpapi.h>
#include <Assert.h>
#pragma comment(lib, "iphlpapi.lib")

char* getMAC();

int main(){ 
  char* pMac = getMAC();
  system("pause");
  free(pMac);
}
char* getMAC() {
  PIP_ADAPTER_INFO AdapterInfo;
  DWORD dwBufLen = sizeof(IP_ADAPTER_INFO);
  char *mac_addr = (char*)malloc(18);

  AdapterInfo = (IP_ADAPTER_INFO *) malloc(sizeof(IP_ADAPTER_INFO));
  if (AdapterInfo == NULL) {
    printf("Error allocating memory needed to call GetAdaptersinfo\n");
    free(mac_addr);
    return NULL; // it is safe to call free(NULL)
  }

  // Make an initial call to GetAdaptersInfo to get the necessary size into the dwBufLen variable
  if (GetAdaptersInfo(AdapterInfo, &dwBufLen) == ERROR_BUFFER_OVERFLOW) {
    free(AdapterInfo);
    AdapterInfo = (IP_ADAPTER_INFO *) malloc(dwBufLen);
    if (AdapterInfo == NULL) {
      printf("Error allocating memory needed to call GetAdaptersinfo\n");
      free(mac_addr);
      return NULL;
    }
  }

  if (GetAdaptersInfo(AdapterInfo, &dwBufLen) == NO_ERROR) {
    // Contains pointer to current adapter info
    PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;
    do {
      // technically should look at pAdapterInfo->AddressLength
      //   and not assume it is 6.
      sprintf(mac_addr, "%02X:%02X:%02X:%02X:%02X:%02X",
        pAdapterInfo->Address[0], pAdapterInfo->Address[1],
        pAdapterInfo->Address[2], pAdapterInfo->Address[3],
        pAdapterInfo->Address[4], pAdapterInfo->Address[5]);
      printf("Address: %s, mac: %s\n", pAdapterInfo->IpAddressList.IpAddress.String, mac_addr);
      // print them all, return the last one.
      // return mac_addr;

      printf("\n");
      pAdapterInfo = pAdapterInfo->Next;        
    } while(pAdapterInfo);                        
  }
  free(AdapterInfo);
  return mac_addr; // caller must free.
}

关于c++ - 如何使用 C++ 在 Windows 中获取 MAC 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13646621/

相关文章:

java - JNA 库,缺少 Windows 函数 : how to add new functions?

windows - 在 Qt 中禁用进度条动画

windows - 常规 dll 与扩展 dll

linux - 是否有 Linux 或 U-Boot 支持在启动时从芯片读取 MAC 地址?

c++ - NiceMock 一个将另一个 Mock 作为构造函数参数的 Mock

c++ - 将非静态成员函数作为函数的参数传递

c++ - 内联变量如何工作?

c++ - 来自命名管道的ifstream-检查是否无阻塞,是否有数据

php - 使用 PHP 查找客户端的 mac 地址

guid - 您生成的 GUID 识别您的身份有多容易?