Wednesday, September 17, 2014

Visual C++ 내 IP 알아내기


#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#pragma warning(push)
#pragma warning(disable: 4127)

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

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

#include <stdio.h>
#include <stdlib.h>

#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
/* Note: could also use malloc() and free() */

// Global variables
ULONG  ulOutBufLen;
DWORD  dwRetVal;

int main() {

/* variables used for GetNetworkParams */
  FIXED_INFO  *pFixedInfo;
  IP_ADDR_STRING  *pIPAddr;

/* variables used for GetAdapterInfo */
  IP_ADAPTER_INFO  *pAdapterInfo;
  IP_ADAPTER_INFO  *pAdapter;
  UINT  dwAddrLen;

/* variables used for GetInterfaceInfo */
  IP_INTERFACE_INFO*  pInterfaceInfo;

/* variables used for GetIpAddrTable */
  MIB_IPADDRTABLE  *pIPAddrTable;
  DWORD  dwSize;
  struct in_addr  IPAddr;
  char  *strIPAddr;

/* variables used for AddIpAddress */
  UINT  iaIPAddress;
  UINT  imIPMask;
  ULONG  NTEContext;
  ULONG  NTEInstance;

/* variables used for GetIpStatistics */
  MIB_IPSTATS  *pStats;

/* variables used for GetTcpStatistics */
  MIB_TCPSTATS  *pTCPStats;

 printf("------------------------\n");
  printf("This is GetAdaptersInfo\n");
  printf("------------------------\n");


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

  if (GetAdaptersInfo( pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
    FREE (pAdapterInfo);
    pAdapterInfo = (IP_ADAPTER_INFO *) MALLOC (ulOutBufLen);
    if (pAdapterInfo == NULL) {
      printf("Error allocating memory needed to call GetAdapterInfo\n");
      return 1;
    }
  }

  if ((dwRetVal = GetAdaptersInfo( pAdapterInfo, &ulOutBufLen)) != NO_ERROR) {
    printf("GetAdaptersInfo call failed with %d\n", dwRetVal);
    return 1;
  }
  pAdapter = pAdapterInfo;

  while (pAdapter) {
    printf("\tIP Address: \t%s\n", pAdapter->IpAddressList.IpAddress.String);
    pAdapter = pAdapter->Next;
  }
 FREE(pAdapterInfo);

  return 0;

#pragma warning(pop)

}

No comments:

Post a Comment