#include "iphlpapi.h"#include#include#include
using namespacestd;//#pragma comment(lib, "Iphlpapi.lib")
static const char *registPath = "System\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}";//HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}\{084BD7D4-9C01-4716-9EBC-6E41C5585050}\Connection//Name : Ethernet//PnPInstanceId : PCI\VEN_8086&DEV_15E3&SUBSYS_224D17AA&REV_31\3&11583659&1&FE
bool isLocalAdapter(const char *pAdapterName);void macAddressToString(const LPBYTE Address, LPSTR lpsz, int nAddressLength = 6);int getPhysicalMacAddress(char *mac);int main(int argc, char const *argv[])
{char mac[64];int ret =getPhysicalMacAddress(mac);if (ret == 0)
{
printf("mac is : %s", mac);
}else{
printf("can't get mac(%d)", ret);
}return 0;
}int getPhysicalMacAddress(char *mac)
{
PIP_ADAPTER_INFO pAdapterInfo;
DWORD AdapterInfoSize= 0;
DWORD dwRetVal= 0;
GetAdaptersInfo(NULL,&AdapterInfoSize);
pAdapterInfo=(PIP_ADAPTER_INFO)GlobalAlloc(GPTR, AdapterInfoSize);
GetAdaptersInfo(pAdapterInfo,&AdapterInfoSize);
PIP_ADAPTER_INFO pAdapter=pAdapterInfo;while(pAdapter)
{if (isLocalAdapter(pAdapter->AdapterName))
{
macAddressToString(pAdapter->Address, mac, pAdapter->AddressLength);
printf("adapter name : %s,%s,%s\n", pAdapter->AdapterName, mac, pAdapter->Description);
pAdapter= pAdapter->Next;//break;
}else{
pAdapter= pAdapter->Next;
}
}
GlobalFree(pAdapterInfo);return 0;
}bool isLocalAdapter(const char *pAdapterName)
{char buffers[MAX_PATH + 1] = {0};
DWORD dwDataLen=MAX_PATH;
DWORD dwType=REG_SZ;
HKEY hLocalNet=NULL;// sprintf(buffers, "%s\\%s\\Connection", registPath, pAdapterName);if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, buffers, 0, KEY_READ, &hLocalNet) !=ERROR_SUCCESS)
{
RegCloseKey(hLocalNet);return false;
}
dwDataLen=MAX_PATH;
memset(buffers,0, sizeof(buffers));if (RegQueryValueEx(hLocalNet, "PnpInstanceID", 0, &dwType, (BYTE *)buffers, &dwDataLen) !=ERROR_SUCCESS)
{
RegCloseKey(hLocalNet);return false;
}//注册表中网卡信息中该项值中的"PCI"并不都位于最前
string PnpInstanceID =buffers;int ret = PnpInstanceID.find("PCI");if (ret == -1)
{
RegCloseKey(hLocalNet);return false;
}//get name//Ethernet Wi-Fi
if (RegQueryValueEx(hLocalNet, "Name", 0, &dwType, (BYTE *)buffers, &dwDataLen) ==ERROR_SUCCESS)
{
printf("name(type):%s\n", buffers);
}else{
printf("can't get name\n");
}
RegCloseKey(hLocalNet);return true;
}void macAddressToString(const LPBYTE Address, LPSTR lpsz, intnAddressLength)
{
LPSTR p=lpsz;for (int i = 0; i < nAddressLength; i++)
{
p+= sprintf(p, i ? ":%02x" : "%02x", Address[i]);
}
}