2014-02-20 55 views
0

我已經編寫了一些代碼來初始化COM並通過使用WMI查詢Win32_NetworkAdapter類來枚舉連接到PC的網絡適配器。我需要使用WMI的原因是我需要枚舉的適配器在此時被禁用,但我仍然需要找出它的InterfaceIndex,並使用GetInterfaceInfo只檢測啓用的適配器。這一切都編譯和運行,但在行:在C++中使用WMI來獲取適配器的InterfaceIndex

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

您似乎已經忽略了Win32_NetworkAdapter類的棄用。你有沒有嘗試過替代品,MSFT_NetAdapter? – rrirower

+0

嗯,我們有另一個庫,它使用Win32_NetworkAdapter類,但在C#中,並在同一平臺上工作,所以肯定不能棄用? –

回答

1

的解決方案是使用具有CoInitializeSecurity和CoSexProxyBlanket而非RPC_C_IMP_LEVEL_IMPERSONATE的RPC_C_IMP_LEVEL_DELEGATE參數。

相關問題