Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enumerate network adapters and get their MAC addresses in Win32 API C++?

Tags:

c++

winapi

How do I enumerate network adapters and get their MAC addresses in Win32 API C++?

like image 623
Maciek Avatar asked Nov 04 '09 14:11

Maciek


People also ask

How do I find MAC address programming?

the file /sys/class/net/eth0/address carries your mac adress as simple string you can read with fopen() / fscanf() / fclose() .


1 Answers

This code should work:

{
    ULONG outBufLen = 0;
    DWORD dwRetVal = 0;
    IP_ADAPTER_INFO* pAdapterInfos = (IP_ADAPTER_INFO*) malloc(sizeof(IP_ADAPTER_INFO));

    // retry up to 5 times, to get the adapter infos needed
    for( int i = 0; i < 5 && (dwRetVal == ERROR_BUFFER_OVERFLOW || dwRetVal == NO_ERROR); ++i )
    {
        dwRetVal = GetAdaptersInfo(pAdapterInfos, &outBufLen);
        if( dwRetVal == NO_ERROR )
        {
            break;
        }
        else if( dwRetVal == ERROR_BUFFER_OVERFLOW )
        {
            free(pAdapterInfos);
            pAdapterInfos = (IP_ADAPTER_INFO*) malloc(outBufLen);
        }
        else
        {
            pAdapterInfos = 0;
            break;
        }
    }
    if( dwRetVal == NO_ERROR )
    {
        IP_ADAPTER_INFO* pAdapterInfo = pAdapterInfos;
        while( pAdapterInfo )
        {
            IP_ADDR_STRING* pIpAddress = &(pAdapterInfo->IpAddressList);
            while( pIpAddress != 0 )
            {
                          // 
                          // <<<<
                          // here pAdapterInfo->Address should contain the MAC address
                          // >>>>
                          // 

                pIpAddress = pIpAddress->Next;
            }
            pAdapterInfo = pAdapterInfo->Next;
        }
    }
    free(pAdapterInfos);
    return false;
}
like image 63
Christopher Avatar answered Oct 08 '22 10:10

Christopher