Gold mine of Visual C++ tricks!
Posts tagged Iphlpapi.h
How to get the MAC address of your network adapter.
61460 days
![]()
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?
![]()
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.
#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<PIP_ADAPTER_INFO>(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 :" << pAdapterInfo->AdapterName << " "
<< "MAC :" << (LPCTSTR) csMacAddress << endl;
// Get next adapter info.
pAdapterInfo = pAdapterInfo->Next;
}
// deallocate the buffer.
delete[] pBuffer;
![]()
Don’t forget to add Iphlpapi.lib to project settings.
![]()
Targeted Audience – Beginners.