我需要一些关于MAC地址的帮助。我需要使用C++编写代码来获取它,所以能否有人帮助我?我已经尝试了很多无用的代码。如果存在任何特定的方法或库,我应该学习如何查找MAC地址,我会非常高兴如果有人能够给我一个链接或者其他更多的信息。
我需要一些关于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.
}
return mac_addr;
发生,那么 free(AdapterInfo);
就不会发生。
另一个问题是,如果 return mac_addr;
没有发生,函数就不会返回任何内容。
但基本思路似乎是正确的。 - Tsar Ioannmac_addr = (char*)malloc(17);
应该改为 mac_addr = (char*)malloc(18);
这样就有空间来终止字符串。 - Jesse Chisholm