Visual Studio .NET 2002Visual C++ 8.0Visual Studio 6Visual Studio .NET 2003Windows 2003Visual Studio 2005Windows 2000Windows XP中级开发Visual StudioWindowsC++
使用 WMI 获取网络适配器 MAC 地址






3.60/5 (5投票s)
使用 WMI 获取网络适配器 MAC 地址
引言
这段代码示例有两个目的
- 它将向您介绍为什么要在 C++ 中使用所有这些丰富的 WMI 类。
- 它将演示一种获取计算机网络适配器 MAC 地址的替代方法。
背景
我在使用 Platform SDK 中的 RPC 函数 UuidCreateSequential
时遇到了这个问题,突然在几台计算机上,它每次都给出不同的 MAC 地址。然后我在 MSDN 上找到了以下声明
“出于安全原因,
UuidCreate
已被修改,不再使用机器的 MAC 地址来生成 UUID。”
所以我不得不找到另一种方法。一种是使用 NetBIOS
函数,但首先,它相当复杂,其次,并非每台机器都安装了 NetBIOS
。所以我转向了 WMI 替代方案,结果非常简单。
Using the Code
在附带的 ZIP 文件中,您将找到一个控制台应用程序,它只是打印出所有网络适配器的 MAC 地址。所有代码都在主函数中,所以这里附带一些解释
int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(NULL); // Initialize COM
try
{
//Create the locator object through which we will
//access all the other WMI functions
WbemScripting::ISWbemLocatorPtr locator;
locator.CreateInstance(WbemScripting::CLSID_SWbemLocator);
if (locator != NULL)
{
// Get the pointer to the WMI service on the active computer
// (the local machine)
WbemScripting::ISWbemServicesPtr services =
locator->ConnectServer(".","root\\cimv2","","","","",0,NULL);
// Get the list of objects of interest, in our case the network adaptors
WbemScripting::ISWbemObjectSetPtr objects =
services->ExecQuery("Select * from Win32_NetworkAdapter",
"WQL",0x10,NULL);
// Create the enumerator for the collection
IEnumVARIANTPtr obj_enum = objects->Get_NewEnum();
ULONG fetched;
VARIANT var;
// Iterate through the collection
while (obj_enum->Next(1,&var,&fetched) == S_OK)
{
// Get an object (an instance of Network adaptor WMI class)
WbemScripting::ISWbemObjectPtr object = var;
// Retrieve the properties
WbemScripting::ISWbemPropertySetPtr properties = object->Properties_;
// Check the adaptor's type by retrieving the "AdapterTypeID" property
WbemScripting::ISWbemPropertyPtr prop =
properties->Item("AdapterTypeID",0);
_variant_t value = prop->GetValue();
if (value.vt == VT_I4 && (int)value == 0) // If LAN adaptor
{
//Retrieve the "MACAddress" property
prop = properties->Item("MACAddress",0);
// And print it out
printf("MAC address found: %s\n",
(const char*)_bstr_t(prop->GetValue()));
}
}
}
}
// In case there was an error, print it out...
catch (_com_error err)
{
printf("Error occurred: %S",err.ErrorMessage());
}
CoUninitialize();
return 0;
}
历史
- 2007 年 3 月 25 日:初始发布