gpt4 book ai didi

c++ - 在C++中使用WMI获取适配器的InterfaceIndex

转载 作者:行者123 更新时间:2023-11-28 07:04:51 25 4
gpt4 key购买 nike

我已经编写了一些代码来初始化 COM,并通过查询 Win32_NetworkAdapter 枚举连接到 PC 的网络适配器。使用 WMI 类。我需要使用 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;

最佳答案

更正/解决方案是将 RPC_C_IMP_LEVEL_DELEGATE 参数与 CoInitializeSecurity 和 CoSetProxyBlanket 一起使用,而不是使用 RPC_C_IMP_LEVEL_IMPERSONATE。

关于c++ - 在C++中使用WMI获取适配器的InterfaceIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21915461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com