解析域名

#include
#include

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


// 版本1

int main()
{
int status;
WSADATA WSAData;
char szTemp1[80];
struct in_addr addr;
if ((status = WSAStartup(MAKEWORD(2, 2), &WSAData)) != 0)
{
return -1;
}

//phe = gethostbyname("www.g.cn");
struct addrinfo *answer, hint, *curr;
char ipstr[16];
ZeroMemory(&hint, sizeof(hint));
hint.ai_family = AF_INET;
hint.ai_socktype = SOCK_STREAM;


if (0 != getaddrinfo("www.baidu.com", NULL, &hint, &answer))
{
return -1;
}
else
{
for (curr = answer; curr != NULL; curr = curr->ai_next) {
inet_ntop(AF_INET,&(((struct sockaddr_in *)(curr->ai_addr))->sin_addr),ipstr, 16);
printf("%s\n", ipstr);
}
}


system("pause");
}


// 版本2

int main()

{

int status;
WSADATA WSAData;
char szTemp1[80];
struct in_addr addr;
if ((status = WSAStartup(MAKEWORD(2, 2), &WSAData)) != 0)
{
return _T("");
}


PHOSTENT phe; 


int nBytes = WideCharToMultiByte(CP_ACP,0,strDomain,strDomain.GetLength(),NULL,0,NULL,NULL);
char* pDomain = new char[ nBytes + 1];
memset(pDomain,0,strDomain.GetLength() + 1);
WideCharToMultiByte(CP_OEMCP, 0, strDomain, strDomain.GetLength(), pDomain, nBytes, NULL, NULL); 
pDomain[nBytes] = 0; 


phe = gethostbyname(pDomain); 
if (phe == NULL) 
{
delete []pDomain;
return _T("");

else
{
addr.s_addr = *(u_long *) phe->h_addr_list[0]; 
}
delete []pDomain;
CString strIP = inet_ntoa(addr);

}

你可能感兴趣的:(解析域名)