출처 : http://www.codeproject.com/useritems/MAC_address_throuh_WMI.asp
Introduction
This sample piece of code has two purposes:
First it will give you general background on who to use all this rich set of WMI classes in C++.
Second it will demonstrate an alternative method for obtaining a MAC address of the network card of the computer.
Background
I have stambled on this problem while I was using the RPC functionUuidCreateSequential
from Platform SDK when suddenly on several computers it began to give different MACs every time than 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 NetBIOS function , but first: it's quite complicated and second: not every machine has NetBIOS installed, so I turned to the WMI alternative wich turned to be quite simple
Using the code
In the attached ZIP file you will find a console applicatio that just print's out all the network card's MACs , all the code is in the main function , so here it is with some explanations:
History
int_tmain(intargc, _TCHAR* argv[]){ CoInitialize(NULL);// Initialize COMtry{//Create the locator object through with we will access alll the other WMI functionsWbemScripting::ISWbemLocatorPtr locator; locator.CreateInstance(WbemScripting::CLSID_SWbemLocator);if(locator != NULL) {// Get the pointer to the WMI service on the active computer (the local mashine)WbemScripting::ISWbemServicesPtr services = locator->ConnectServer(".","root\\cimv2","","","","",0,NULL);// Get thee list of objects of interest , in our case the network adaptorsWbemScripting::ISWbemObjectSetPtr objects = services->ExecQuery("Select * from Win32_NetworkAdapter","WQL",0x10,NULL);// Create the enumerator for the collectionIEnumVARIANTPtr obj_enum = objects->Get_NewEnum(); ULONG fetched; VARIANT var;// Iterate through the collectionwhile(obj_enum->Next(1,&var,&fetched) == S_OK) {// Get an object (an instance of Network adaptor WMI class)WbemScripting::ISWbemObjectPtr object = var;// Retrieve the propertiesWbemScripting::ISWbemPropertySetPtr properties = object->Properties_;// Chesk the adaptor's type by retrieving the "AdapterTypeID" propertyWbemScripting::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" propertyprop = properties->Item("MACAddress",0);// And print it outprintf("MAC address found: %s\n",(constchar*)_bstr_t(prop->GetValue())); } } } }// In case there was an error print it out...catch(_com_error err) { printf("Error ocured: %S",err.ErrorMessage()); } CoUninitialize();return0;}
About Alex Hazanov
'Windows' 카테고리의 다른 글
Programming Windows TCP Sockets in C++ for the Beginner (0) | 2007.04.13 |
---|---|
Top 10 Tips for Using Windows PowerShell (0) | 2006.11.13 |
Windows 시스템레벨 개발자에게 도움이 되는 사이트 (0) | 2006.11.10 |