我已经编写了一些代码来初始化COM,并通过使用WMI查询Win32_NetworkAdapter类来枚举连接到PC的网络适配器。我需要使用WMI的原因是我需要枚举的适配器在当时被禁用,但我仍然需要找到它的InterfaceIndex,并且使用GetInterfaceInfo只检测启用的适配器。这一切都编译并运行,但在线:
hr = pEnumerator->Next(WBEM_INFINITE, 1, &pClassObj, &ulReturnVal);
用于检索第一个适配器,它不返回任何设备和垃圾HRESULT。我使用this页面上的示例作为我的指导。
CoInitialize(NULL); // Initialize COM
HRESULT hr = NULL;
hr = CoInitializeSecurity(
NULL, // security descriptor
-1, // use this simple setting
NULL, // use this simple setting
NULL, // reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // authentication level
RPC_C_IMP_LEVEL_IMPERSONATE, // impersonation level
NULL, // use this simple setting
EOAC_NONE, // no special capabilities
NULL); // reserved
if (FAILED(hr))
{
CoUninitialize();
return -1;
}
IWbemLocator *pLoc = 0;
hr = CoCreateInstance(CLSID_WbemLocator, 0,
CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc);
if (FAILED(hr))
{
CoUninitialize();
return -1; // Program has failed.
}
IWbemServices *pSvc = 0;
// Connect to the root\default namespace with the current user.
hr = pLoc->ConnectServer( _bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
if (FAILED(hr))
{
pLoc->Release();
CoUninitialize();
return -1; // Program has failed.
}
hr = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,
RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
if (FAILED(hr))
{
pSvc->Release();
pLoc->Release();
CoUninitialize();
return -1; // Program has failed.
}
IEnumWbemClassObject* pEnumerator = NULL;
hr = pSvc->ExecQuery(bstr_t("WQL"), bstr_t("SELECT * FROM Win32_NetworkAdapter"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
if (FAILED(hr))
{
pSvc->Release();
pLoc->Release();
CoUninitialize();
return -1;
}
IWbemClassObject *pClassObj;
ULONG ulReturnVal;
while ( pEnumerator )
{
hr = pEnumerator->Next(WBEM_INFINITE, 1, &pClassObj, &ulReturnVal);
// code would go here to obtain the adapter properties.
pClassObj->Release();
}
return -1;
答案 0 :(得分:1)
解决方案是使用带有CoInitializeSecurity和CoSexProxyBlanket的RPC_C_IMP_LEVEL_DELEGATE参数,而不是RPC_C_IMP_LEVEL_IMPERSONATE。