Recommanded Free YOUTUBE Lecture: <% selectedImage[1] %>

설명

자신의 아이피를 얻어오는 함수의 윈도우즈 버전입니다. WinXP 이상에서만 정상 작동합니다.

사용방법

소스코드에 'todo' 주석을 참고 하십시오.

코드

//------------------------------------------------------------------------------
//
// Get machine ip addresses by sockaddr for sockaddr_in/sockaddr_in6.
//
// AUTHOR  : Yubin Lim
// DATE    : 2004-11-05
// EMAIL   : purewell at purewell dot biz
// REQUIRE : MICROSOFT PLATFORM SDK(IPHLPAPI.LIB),
//           WINDOWS XP,
//           Visual C/C++ Compiler
//
//------------------------------------------------------------------------------


#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

#include <winsock2.h>
#include <ws2tcpip.h>
#include <iptypes.h>
#include <iphlpapi.h>

#pragma comment(lib, "iphlpapi")
#pragma comment(lib, "ws2_32")

static bool win32_getMyIP(int nFamily)
{
  DWORD dwRet;
  PIP_ADAPTER_ADDRESSES pAdpAddrs;
  PIP_ADAPTER_ADDRESSES pThis;
  PIP_ADAPTER_UNICAST_ADDRESS pThisAddrs;
  unsigned long ulBufLen = sizeof(IP_ADAPTER_ADDRESSES);

  pAdpAddrs = (PIP_ADAPTER_ADDRESSES)malloc( ulBufLen );
  if ( !pAdpAddrs ) return false;

  dwRet = GetAdaptersAddresses(nFamily, 0, NULL, pAdpAddrs, &ulBufLen);
  if (dwRet == ERROR_BUFFER_OVERFLOW)
  {
    free ( pAdpAddrs );
    pAdpAddrs = (PIP_ADAPTER_ADDRESSES)malloc( ulBufLen );

    if ( !pAdpAddrs ) return false;
  }

  dwRet = GetAdaptersAddresses(nFamily, 0, NULL, pAdpAddrs, &ulBufLen);
  if ( dwRet != NO_ERROR )
  {
    free ( pAdpAddrs );
    return false;
  }

  for ( pThis = pAdpAddrs; NULL != pThis; pThis = pThis->Next)
  {
    fprintf(stderr," FN: %S\n", pThis->FriendlyName);
    fprintf(stderr," DS: %S\n", pThis->Description);
    fprintf(stderr," AN: %S\n", pThis->AdapterName);
    for ( pThisAddrs = pThis->FirstUnicastAddress;
          NULL != pThisAddrs;
          pThisAddrs = pThisAddrs->Next )
    {
      if ( nFamily == AF_INET )
      {
        struct sockaddr_in* pAddr
          = (struct sockaddr_in*)pThisAddrs->Address.lpSockaddr;

        cerr << "  IP v4: " << inet_ntoa(pAddr->sin_addr) << endl;
      }
      else if ( nFamily == AF_INET6 )
      {
        struct sockaddr_in6* pAddr
          = (sockaddr_in6*)pThisAddrs->Address.lpSockaddr;

        //! @todo convert binary address type to string type
        cerr << "  IP v6" << endl;
      }
    }//for
  }//for

  free ( pAdpAddrs );

  return true;
}

변경사항

2004/11/05