如何在Windows中使用C ++获取MAC地址? [英] How to get MAC Address in Windows with C++?

查看:411
本文介绍了如何在Windows中使用C ++获取MAC地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些有关MAC地址的帮助.我必须通过在C ++中使用一些代码来获得它,所以有人可以帮助我吗?我已经尝试了很多无用的代码.如果存在我应该学习以找到MAC地址的任何特定方法或库,如果有人给我传递链接或更多有关此方面的知识,我将非常高兴.

I need some help with MAC addresses. I have to get it by using some code in C++ so could anybody help me with this? I've already tried a lot of useless codes. If exists any specific method or lib that I should study to find the MAC address, I will be very happy if anybody pass me a link or something to know more about this.

推荐答案

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

I got it people! Me and a guy from the work solve this using this code:

#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.
}

这篇关于如何在Windows中使用C ++获取MAC地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆