Search This Blog

Monday, December 22, 2008

How to get the MAC address of your Network Adapter.

Description
MAC address stands for “Media Access Control“ address which is 6 bytes( 48 bits ) long. MAC address is the unique address which is used to identify network interface hardware. So how to get the MAC address of your network adapter?

How to Do?
You can use the function - GetAdaptersInfo(). The network adapter information will be populated and filled back in IP_ADAPTER_INFO structure. In that structure, you can get the network adapter name, MAC address and a couple of other information. See the sample code snippet.

Code:
#include "Iphlpapi.h"
...
// Get the buffer length required for IP_ADAPTER_INFO.
ULONG BufferLength = 0;
BYTE* pBuffer = 0;
if( ERROR_BUFFER_OVERFLOW == GetAdaptersInfo( 0, &BufferLength ))
{
// Now the BufferLength contain the required buffer length.
// Allocate necessary buffer.
pBuffer = new BYTE[ BufferLength ];
}
else
{
// Error occurred. handle it accordingly.
}
// Get the Adapter Information.
PIP_ADAPTER_INFO pAdapterInfo = reinterpret_cast(pBuffer);
GetAdaptersInfo( pAdapterInfo, &BufferLength );
// Iterate the network adapters and print their MAC address.
while( pAdapterInfo )
{
// Assuming pAdapterInfo->AddressLength is 6.
CString csMacAddress;
csMacAddress.Format(_T("%02x:%02x:%02x:%02x:%02x:%02x"),
pAdapterInfo->Address[0],
pAdapterInfo->Address[1],
pAdapterInfo->Address[2],
pAdapterInfo->Address[3],
pAdapterInfo->Address[4],
pAdapterInfo->Address[5]);
cout << "Adapter Name :" <<>AdapterName << " "<< "MAC :" << (LPCTSTR)csMacAddress << padapterinfo =" pAdapterInfo-">Next;
}
// deallocate the buffer.
delete[] pBuffer;


PS : Dont forget to add Iphlpapi.lib to project settings.

No comments:

Post a Comment