下,可以通过访问注册表获取mac地址,可是非常可惜的是有些系统的注册表不提供这个键值,另外也可以通过
DeviceIoControl这类函数获得,但是所有方法要么不全面,要么不够简单或者有些平台bsp包根本就不支持,我捉摸了一个比较通用的方法,通过SendArp函数来获得,下面是代码,用起来比较简单,查msdn,获得方法如下
-
-
-
- #include <windows.h>
- #include <stdio.h>
- #include <tchar.h>
- #include <iphlpapi.h>
-
- int __cdecl main()
- {
- HRESULT hr;
- IPAddr ipAddr;
- ULONG pulMac[2];
- ULONG ulLen;
- ipAddr = inet_addr ("192.168.25.31");
- memset (pulMac, 0xff, sizeof (pulMac));
- ulLen = 6;
-
- hr = SendARP (ipAddr, 0, pulMac, &ulLen);
- printf ("Return %08x, length %8d/n", hr, ulLen);
-
- size_t i, j;
- char * szMac = new char[ulLen*3];
- PBYTE pbHexMac = (PBYTE) pulMac;
-
-
-
- for (i = 0, j = 0; i < ulLen - 1; ++i) {
- j += sprintf (szMac + j, "%02X:", pbHexMac[i]);
- }
-
- sprintf (szMac + j, "%02X", pbHexMac[i]);
- printf ("MAC address %s/n", szMac);
-
- delete [] szMac;
- return 0;
- }
// // Link with ws2_32.lib and iphlpapi.lib // #include <windows.h> #include <stdio.h> #include <tchar.h> #include <iphlpapi.h> int __cdecl main() { HRESULT hr; IPAddr ipAddr; ULONG pulMac[2]; ULONG ulLen; ipAddr = inet_addr ("192.168.25.31");//设备自身的ip memset (pulMac, 0xff, sizeof (pulMac)); ulLen = 6; hr = SendARP (ipAddr, 0, pulMac, &ulLen); printf ("Return %08x, length %8d/n", hr, ulLen); size_t i, j; char * szMac = new char[ulLen*3]; PBYTE pbHexMac = (PBYTE) pulMac; // // Convert the binary MAC address into human-readable // for (i = 0, j = 0; i < ulLen - 1; ++i) { j += sprintf (szMac + j, "%02X:", pbHexMac[i]); } sprintf (szMac + j, "%02X", pbHexMac[i]); printf ("MAC address %s/n", szMac); delete [] szMac; return 0; }
需要注意的是本机ip不能用环回地址,否则SendArp操作会失败
获得本机ip的方法很多,这里不列举,访问注册表即可