|
++获取windows正在使用的网卡的MAC地址
这个方法是stackoverflow上找到的,在这做个记录,相关的头文件请查找我之前的文章
TCHAR szMac[MAX_PATH] = { 0 };
int nBuffSize = MAX_PATH;
std::string nError = "";
if (szMac == NULL || nBuffSize < 18) return nError;
HKEY hKey = NULL;
HKEY hKey2 = NULL;
TCHAR szKey[MAX_PATH], szBuffer[MAX_PATH];
TCHAR szServiceName[MAX_PATH];
TCHAR szFileName[MAX_PATH] = { 0 };
DWORD dwRet = 0;
DWORD dwType = 0;
DWORD cbData = 0;
DWORD cName = _countof(szBuffer);
if (RegOpenKey(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards\\"), &hKey) != ERROR_SUCCESS)
return nError;
for (int i = 0; RegEnumKeyEx(hKey, i, szBuffer, &cName, NULL, NULL, NULL, NULL) == ERROR_SUCCESS; ++i, cName = _countof(szBuffer))
{
_tcscpy_s(szKey, MAX_PATH, _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards\\"));
_tcscat_s(szKey, MAX_PATH, szBuffer);
if (RegOpenKey(HKEY_LOCAL_MACHINE, szKey, &hKey2) != ERROR_SUCCESS)
{
continue;
}
dwType = REG_SZ;
cbData = MAX_PATH * sizeof(TCHAR);
if (RegQueryValueEx(hKey2, _T("ServiceName"), NULL, &dwType, (LPBYTE)szServiceName, &cbData) == ERROR_SUCCESS)
{
//读取成功后关闭句柄
RegCloseKey(hKey2);
_tcscpy_s(szFileName, MAX_PATH, _T("\\\\.\\"));
_tcscat_s(szFileName, MAX_PATH, szServiceName);
HANDLE hFile = CreateFile(szFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
DWORD dwInBuff = 0x01010101;
BYTE outBuff[MAX_PATH];
dwRet = DeviceIoControl(hFile, 0x00170002, &dwInBuff, sizeof(dwInBuff), outBuff, sizeof(outBuff), &cbData, NULL);
//无论成功失败关闭文件句柄
CloseHandle(hFile);
hFile = INVALID_HANDLE_VALUE;
if (dwRet)
{
_stprintf_s(
szMac, nBuffSize / sizeof(TCHAR),
_T("%02X-%02X-%02X-%02X-%02X-%02X"),
outBuff[0], outBuff[1], outBuff[2],
outBuff[3], outBuff[4], outBuff[5]
);
break;
}
}
}
else
{
//读取失败关闭句柄
RegCloseKey(hKey2);
}
}//end for
if (hKey != NULL)
{
RegCloseKey(hKey);
}
std::string MAC;
int iLen = WideCharToMultiByte(CP_ACP, 0, szMac, -1, NULL, 0, NULL, NULL);
char* chRtn = new char[iLen * sizeof(char)];
WideCharToMultiByte(CP_ACP, 0, szMac, -1, chRtn, iLen, NULL, NULL);
MAC = chRtn;
return MAC;
[code]原文链接:https://blog.csdn.net/mengxingchengshang/article/details/119574875[/code] |
|