【问题标题】:how can i get get the MACaddress of all the NICs on my PC using WMI如何使用 WMI 获取 PC 上所有 NIC 的 MAC 地址
【发布时间】:2010-12-02 13:58:32
【问题描述】:

大家好,

我正在尝试修改MS提供的代码尝试访问网络适配器配置

当我尝试使用 VC++ 2005 访问 Mac 地址或 IPAddress 属性时,出现空指针异常。检查 // 此处的异常:vtProp 返回为 NULL 行得到异常。

#define _WIN32_DCOM
#include "stdafx.h"

#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>

# pragma comment(lib, "wbemuuid.lib")
#pragma comment(lib, "comsuppw.lib")

int _tmain(int argc, _TCHAR* argv[])
{
      HRESULT hres;

    // Step 1: --------------------------------------------------
    // Initialize COM. ------------------------------------------

    hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
    if (FAILED(hres))
    {
        cout << "Failed to initialize COM library. Error code = 0x" 
            << hex << hres << endl;
        return 1;                  // Program has failed.
    }

    // Step 2: --------------------------------------------------
    // Set general COM security levels --------------------------
    // Note: If you are using Windows 2000, you need to specify -
    // the default authentication credentials for a user by using
    // a SOLE_AUTHENTICATION_LIST structure in the pAuthList ----
    // parameter of CoInitializeSecurity ------------------------

    hres =  CoInitializeSecurity(
        NULL, 
        -1,                          // COM authentication
        NULL,                        // Authentication services
        NULL,                        // Reserved
        RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication 
        RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
        NULL,                        // Authentication info
        EOAC_NONE,                   // Additional capabilities 
        NULL                         // Reserved
        );


    if (FAILED(hres))
    {
        cout << "Failed to initialize security. Error code = 0x" 
            << hex << hres << endl;
        CoUninitialize();
        return 1;                    // Program has failed.
    }

    // Step 3: ---------------------------------------------------
    // Obtain the initial locator to WMI -------------------------

    IWbemLocator *pLoc = NULL;

    hres = CoCreateInstance(
        CLSID_WbemLocator,             
        0, 
        CLSCTX_INPROC_SERVER, 
        IID_IWbemLocator, (LPVOID *) &pLoc);

    if (FAILED(hres))
    {
        cout << "Failed to create IWbemLocator object."
            << " Err code = 0x"
            << hex << hres << endl;
        CoUninitialize();
        return 1;                 // Program has failed.
    }

    // Step 4: -----------------------------------------------------
    // Connect to WMI through the IWbemLocator::ConnectServer method

    IWbemServices *pSvc = NULL;

    // Connect to the root\cimv2 namespace with
    // the current user and obtain pointer pSvc
    // to make IWbemServices calls.
    hres = pLoc->ConnectServer(
         _bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
         NULL,                    // User name. NULL = current user
         NULL,                    // User password. NULL = current
         0,                       // Locale. NULL indicates current
         NULL,                    // Security flags.
         0,                       // Authority (e.g. Kerberos)
         0,                       // Context object 
         &pSvc                    // pointer to IWbemServices proxy
         );

    if (FAILED(hres))
    {
        cout << "Could not connect. Error code = 0x" 
             << hex << hres << endl;
        pLoc->Release();     
        CoUninitialize();
        return 1;                // Program has failed.
    }

    cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;


    // Step 5: --------------------------------------------------
    // Set security levels on the proxy -------------------------

    hres = CoSetProxyBlanket(
       pSvc,                        // Indicates the proxy to set
       RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
       RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
       NULL,                        // Server principal name 
       RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
       RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
       NULL,                        // client identity
       EOAC_NONE                    // proxy capabilities 
    );

    if (FAILED(hres))
    {
        cout << "Could not set proxy blanket. Error code = 0x" 
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();     
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 6: --------------------------------------------------
    // Use the IWbemServices pointer to make requests of WMI ----

    // For example, get the name of the operating system
    IEnumWbemClassObject* pEnumerator = NULL;
    hres = pSvc->ExecQuery(
        bstr_t("WQL"), 
        bstr_t("SELECT * FROM Win32_NetworkAdapterConfiguration"),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, 
        NULL,
        &pEnumerator);

    if (FAILED(hres))
    {
        cout << "Query for NIC(s) name failed."
            << " Error code = 0x" 
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 7: -------------------------------------------------
    // Get the data from the query in step 6 -------------------

    IWbemClassObject *pclsObj;
    ULONG uReturn = 0;

    while (pEnumerator)
    {
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, 
            &pclsObj, &uReturn);

        if(0 == uReturn)
        {
            break;
        }

        VARIANT vtProp;

        // Get the value of the Name property

        //hr = pclsObj->Get(L"Caption", 0, &vtProp, 0, 0);
  //      wcout << " Caption : " << vtProp.bstrVal << endl;
  //      VariantClear(&vtProp);
     //   pclsObj->Release();

        hr = pclsObj->Get(L"MACAddress", 0, &vtProp, 0, 0);
        // exception here:  vtProp is returned as NULL
        wcout << " MACAddress : " << vtProp.bstrVal << endl;
        VariantClear(&vtProp);
        pclsObj->Release();


    }

    // Cleanup
    // ========

    pSvc->Release();
    pLoc->Release();
    pEnumerator->Release();
   // pclsObj->Release();
    CoUninitialize();

    return 0;   // Program successfully completed.
}

代码有什么问题??

阿卜杜勒·哈利克

【问题讨论】:

  • hrhr = pclsObj-&gt;Get(L"MACAddress", 0, &amp;vtProp, 0, 0);之后的值是多少?
  • 执行该行后 hr S_OK 的值

标签: com visual-c++ wmi


【解决方案1】:

这很旧,但我遇到了同样的问题,我在任何地方都没有看到解决方案。我通过检查 VT_NULL 解决了这个问题。

if( vtProp.vt != VT_NULL )
    wcout << " MACAddress : " << vtProp.bstrVal << endl;

我不明白为什么某些结果是 VT_NULL,但我怀疑可以通过在“select”语句中添加“where”子句来避免这种情况。

感谢 finnw 的提示!

【讨论】:

    【解决方案2】:

    我会从初始化 vtProp 变量开始——这不重要,但有时 COM 服务器会假设输出参数;

      VariantInit(&vtProp);
    

    然后您可以在返回 vtProp 后检查它并查看实际类型是什么(.vt 成员)——也许它不是字符串,出于某种原因?

    您能否将类型发回(您可以与 oaidl.h 中的 VARTYPE 定义交叉引用以查看友好名称是什么)?

    【讨论】:

      【解决方案3】:

      网络适配器列表通常包含一些“虚拟”适配器,它们并不都有 MAC 地址。有些(例如“Packet Scheduler Miniport”)复制了物理适配器的 MAC 地址。您只需检查vt 字段(可能是VT_EMPTY)并从结果列表中删除重复项。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-08
        • 2020-07-04
        • 2015-04-11
        • 2013-08-24
        • 2012-01-07
        • 1970-01-01
        • 2020-05-20
        • 1970-01-01
        相关资源
        最近更新 更多