获取本机MAC地址

主要还是参考MSDN关于IP_ADAPTER_INFO的描述:

http://msdn.microsoft.com/en-us/library/windows/desktop/aa366062%28v=vs.85%29.aspx


#include <winsock2.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment(lib, "IPHLPAPI.lib")

#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))

int GetMacAddress(char *pMacAddr)
{
    unsigned char pMac[6];
    PIP_ADAPTER_INFO pAdapterInfo = NULL;
    ULONG uLong = sizeof (IP_ADAPTER_INFO);
    int ret = -1;

    ULONG ulOutBufLen = sizeof (IP_ADAPTER_INFO);
    pAdapterInfo = (IP_ADAPTER_INFO *) MALLOC(sizeof (IP_ADAPTER_INFO));
    if (pAdapterInfo == NULL) {
        TRACE("Error allocating memory needed to call GetAdaptersinfo\n");
        return 1;
    }

    // Make an initial call to GetAdaptersInfo to get
    // the necessary size into the ulOutBufLen variable
    if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
        FREE(pAdapterInfo);
        pAdapterInfo = (IP_ADAPTER_INFO *) MALLOC(ulOutBufLen);
        if (pAdapterInfo == NULL) {
            TRACE("Error allocating memory needed to call GetAdaptersinfo\n");
            return 1;
        }
    }

    if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) != NO_ERROR)
    {
        goto EXIT;
    }

    if(NULL == pAdapterInfo)
    {
        goto EXIT;
    }

    ret = 0;
    sprintf(pMacAddr, "%02X:%02X:%02X:%02X:%02X:%02X", 
        pAdapterInfo->Address[0], pAdapterInfo->Address[1], pAdapterInfo->Address[2], 
        pAdapterInfo->Address[3], pAdapterInfo->Address[4], pAdapterInfo->Address[5]);

EXIT:
    if (NULL != pAdapterInfo)
    {
        FREE(pAdapterInfo);
    }

    return ret;
}

你可能感兴趣的:(获取本机MAC地址)