Using WMI in C++ to obtain the InterfaceIndex of a

2019-09-08 07:54发布

问题:

I've written some code to initialise COM and enumerate the network adapters attached to the PC by querying the Win32_NetworkAdapter class using WMI. The reason I need to use WMI is that the adapter I need to enumerate is disabled at the time but I still need to find out its InterfaceIndex, and using GetInterfaceInfo only detects enabled adapters. It all compiles and runs but at the line:

hr = pEnumerator->Next(WBEM_INFINITE, 1, &pClassObj, &ulReturnVal);

which is meant to retrieve the very first adapter, it returns no devices and a garbage HRESULT. I used the example on this page as my guidance.

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;

回答1:

The solution was to use the RPC_C_IMP_LEVEL_DELEGATE parameter with CoInitializeSecurity and CoSexProxyBlanket rather than RPC_C_IMP_LEVEL_IMPERSONATE.



标签: c++ windows wmi