[C++] WinApi: How to Get MacAddress
#pragma comment(lib, "Iphlpapi.lib")
#include "iphlpapi.h"
BOOL GetMacAddress(char *pMacAddr)
{
DWORD dwStatus;
IP_ADAPTER_INFO *pAdapterInfo = NULL;
IP_ADAPTER_INFO *pOriginalPtr = NULL;
ULONG ulSizeAdapterInfo = 0;
dwStatus = GetAdaptersInfo(pAdapterInfo, &ulSizeAdapterInfo);
if (dwStatus == ERROR_BUFFER_OVERFLOW)
{
if (!(pAdapterInfo = (PIP_ADAPTER_INFO)malloc(ulSizeAdapterInfo)))
{
MessageBox(NULL, "Insufficient Memory", "GetMacAddress Error", MB_OK);
return FALSE;
}
dwStatus = GetAdaptersInfo(pAdapterInfo, &ulSizeAdapterInfo);
}
char MacAddr[18];
pOriginalPtr = pAdapterInfo;
if (pAdapterInfo == NULL)
{
MessageBox(NULL, "No Interfaces Present \n", "Error", MB_OK);
return FALSE;
}
while (pAdapterInfo != NULL)
{
if (pAdapterInfo->AddressLength == 6)
{
wsprintf(MacAddr, "%0.2X%0.2X%0.2X%0.2X%0.2X%0.2X\n", \
(DWORD)pAdapterInfo->Address[0], \
(DWORD)pAdapterInfo->Address[1], \
(DWORD)pAdapterInfo->Address[2], \
(DWORD)pAdapterInfo->Address[3], \
(DWORD)pAdapterInfo->Address[4], \
(DWORD)pAdapterInfo->Address[5]);
}
pAdapterInfo = pAdapterInfo->Next;
}
free(pAdapterInfo);
strcpy(pMacAddr, MacAddr);
return TRUE;
};