도메인에서 IP얻어 내는 코드이다.
// GetIPAddressFromSocket.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <list>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <MSWSock.h>
#pragma comment(lib, "ws2_32.lib")
namespace std
{
#ifdef UNICODE
typedef wstring tstring;
#else
typedef string tstring;
#endif
}
bool getDomainIP(const char* domain, __out std::list<std::tstring>& ip_list)
{
struct hostent *pHost = nullptr;
struct in_addr *pAddr = nullptr;
pHost = gethostbyname(domain);
if(pHost == nullptr)
{
return false;
}
while(*pHost->h_addr_list != nullptr){
pAddr = reinterpret_cast<in_addr *>(*(pHost->h_addr_list));
const char* ip = inet_ntoa(*pAddr);
pHost->h_addr_list++;
#ifdef UNICODE
wchar_t wip[64];
mbstowcs(wip, ip, strlen(ip)+1);
ip_list.push_back(wip);
#else
ip_list.push_back(ip);
#endif
}
return true;
}
bool NetworkStartup()
{
WSADATA wsaData;
if (0 != WSAStartup(WINSOCK_VERSION, &wsaData))
{
return false;
}
return true;
}
void NetworkFinish()
{
WSACleanup();
}
int _tmain(int argc, _TCHAR* argv[])
{
if (false == NetworkStartup())
{
return 0;
}
std::list<std::tstring> ipAddress;
getDomainIP("www.google.com", ipAddress);
for each(const auto& ip in ipAddress)
{
_tprintf(_T("ip address(%s)\n"), ip.c_str());
}
NetworkFinish();
return 0;
}
Posted by 약올랑