본문 바로가기
Study/MFC

Mac Address 및 IP 주소 가져오기(#Mac, #IP, #MacAddress)

by 뿡뿡대마왕 2016. 1. 29.
반응형


MacAddress 및 IP 주소를 가져오는 소스 코드 입니다.


출처: http://blog.daum.net/odega/31


어떤식으로 가져오는지 공부해보고, 구찮으니 가져다 씁시다.


#pragma comment(lib, "Iphlpapi.lib")


#include <Iphlpapi.h>

//성공 1, 실패 0 리턴
BOOL GetIP(CStringArray& strIPArray)
{
    CStringA strIPAddress;

    PIP_ADAPTER_INFO pAdapterInfo;
    PIP_ADAPTER_INFO pAdapter = NULL;
    DWORD dwRetVal = 0;

    ULONG ulOutBufLen = sizeof (IP_ADAPTER_INFO);
    pAdapterInfo = new IP_ADAPTER_INFO[ulOutBufLen];

    if (pAdapterInfo == NULL)
        return FALSE;

    if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW)
    {
        delete pAdapterInfo;
        pAdapterInfo = new IP_ADAPTER_INFO[ulOutBufLen];
        if (pAdapterInfo == NULL)
            return FALSE;
    }

    if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR)
    {
        pAdapter = pAdapterInfo;
        while (pAdapter)
        {
            strIPAddress.Format("%s", pAdapter->IpAddressList.IpAddress.String);
            strIPArray.Add(CA2T(strIPAddress));
            pAdapter = pAdapter->Next;
        }
    }

    delete pAdapterInfo;
    pAdapterInfo = NULL;
    return TRUE;
}

//성공 1, 실패 0 리턴
BOOL GetMacAddress(CStringArray& strMacArray, CString strSpecifiedIP)
{
    PIP_ADAPTER_INFO pAdapterInfo;
    PIP_ADAPTER_INFO pAdapter = NULL;
    DWORD dwRetVal = 0;

    ULONG ulOutBufLen = sizeof (IP_ADAPTER_INFO);
    pAdapterInfo = new IP_ADAPTER_INFO[ulOutBufLen];

    if (pAdapterInfo == NULL)
        return FALSE;

    if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW)
    {
        delete pAdapterInfo;
        pAdapterInfo = new IP_ADAPTER_INFO[ulOutBufLen];
        if (pAdapterInfo == NULL)
            return FALSE;
    }

    if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR)
    {
        pAdapter = pAdapterInfo;
        while (pAdapter)
        {
            CStringA strMacAddress;
            strMacAddress.Format("%02X:%02X:%02X:%02X:%02X:%02X",
                pAdapter->Address[0],
                pAdapter->Address[1],
                pAdapter->Address[2],
                pAdapter->Address[3],
                pAdapter->Address[4],
                pAdapter->Address[5]);

            CStringA strIPAddress;
            strIPAddress.Format("%s", pAdapter->IpAddressList.IpAddress.String);

            if(strSpecifiedIP.GetLength() > 0)
            {
                if(strIPAddress.Find(CT2A(strSpecifiedIP)) >= 0)
                {
                    strMacArray.Add(CA2T(strMacAddress));
                    break;
                }
            }
            else
                strMacArray.Add(CA2T(strMacAddress));

            pAdapter = pAdapter->Next;
        }
    }

    delete pAdapterInfo;
    pAdapterInfo = NULL;
    return TRUE;
}


반응형

댓글