How to get the MAC address of your network adapter.

24 05 2008


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.


Actions

Information

2 responses to “How to get the MAC address of your network adapter.”

20 09 2008
Ananth (05:35:31) :

Hello,
From where can I get Iphlpapi.h and Iphlpapi.lib? I am using VC++ 6.0.

Regards
Ananth

19 10 2008
Sachin (06:47:10) :

Ananth, you need to download the Microsoft SDKs which is not included in the Visual C++ 6, that contains new libraries, headers for VC++ 6.

Leave a comment

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>