Introduction
This sample piece of code has two purposes:
- It will give you a general background on why to use all this rich set of WMI classes in C++.
- It will demonstrate an alternative method for obtaining a MAC address of the network card of the computer.
Background
I stumbled upon this problem while I was using the RPC function UuidCreateSequential
from Platform SDK when suddenly on several computers it began to give different MACs every time. Then I found this statement on MSDN:
"For security reasons, UuidCreate
was modified so that it no longer uses a machine's MAC address to generate UUIDs."
So I had to find an alternative method. One was to use the NetBIOS
function, but firstly, it's quite complicated and secondly, not every machine has NetBIOS
installed. So I turned to the WMI alternative which turned to be quite simple.
Using the Code
In the attached ZIP file, you will find a console application that just prints out all the network cards MACs. All the code is in the main function, so here it is with some explanations:
int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(NULL); try
{
WbemScripting::ISWbemLocatorPtr locator;
locator.CreateInstance(WbemScripting::CLSID_SWbemLocator);
if (locator != NULL)
{
WbemScripting::ISWbemServicesPtr services =
locator->ConnectServer(".","root\\cimv2","","","","",0,NULL);
WbemScripting::ISWbemObjectSetPtr objects =
services->ExecQuery("Select * from Win32_NetworkAdapter",
"WQL",0x10,NULL);
IEnumVARIANTPtr obj_enum = objects->Get_NewEnum();
ULONG fetched;
VARIANT var;
while (obj_enum->Next(1,&var,&fetched) == S_OK)
{
WbemScripting::ISWbemObjectPtr object = var;
WbemScripting::ISWbemPropertySetPtr properties = object->Properties_;
WbemScripting::ISWbemPropertyPtr prop =
properties->Item("AdapterTypeID",0);
_variant_t value = prop->GetValue();
if (value.vt == VT_I4 && (int)value == 0) {
prop = properties->Item("MACAddress",0);
printf("MAC address found: %s\n",
(const char*)_bstr_t(prop->GetValue()));
}
}
}
}
catch (_com_error err)
{
printf("Error occurred: %S",err.ErrorMessage());
}
CoUninitialize();
return 0;
}
History
- 25th March, 2007: Initial post