18,356
社区成员
发帖
与我相关
我的任务
分享
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#include<iostream>
using namespace std;
char *hostname="www.tsinghua.edu.cn";
int main()
{
WSADATA data;
if(WSAStartup(0x0202,&data)!=0)
{
cout<<"Failed to start up:"<<WSAGetLastError()<<endl;
return -1;
}
PHOSTENT pHost=gethostbyname(hostname);
if(pHost==NULL)
{
cout<<"Failed to resolve host name:"<<WSAGetLastError()<<endl;
}
cout<<"Host Name:"<<pHost->h_name<<endl;
cout<<"Alias:"<<endl;
for(int i=0;pHost->h_aliases[i]!=NULL;i++)
{
cout<<pHost->h_aliases[i]<<endl;
}
for(int j=0;pHost->h_addr_list[j]!=NULL;j++)
{
in_addr addr;
addr.S_un.S_addr=(LONG)pHost->h_addr_list[j];
cout<<inet_ntoa(addr)<<endl;
}
WSACleanup();
return 0;
}
这个是用WSAAsyncGetHostByName()函数解析的结果:HostName:www.d.tsinghua.edu.cn
Aliases:
www.tsinghua.edu.cn
Address type:IPV4.
244.250.18.0
#define WM_GETHOSTBYNAME
class DemoDlg
{
...
public:
afx_msg void OnGetHostByName(WPARAM wParam,LPARAM lParam);
...
private:
HANDLE m_hGetHost;
char m_host[MAXGETHOSTSTRUCT];
};
CDemoDlg::CDemoDlg()
{
...
m_hGetHostByName=NULL;
}
void CDemoDlg::OnGetHostByName(WPARAM wParam,LPARAM lParam)
{
HANDLE hGetHost=(HANDLE)wParam;
if (hGetHost==m_hGetHost)
{
if (WSAGETASYNCERROR(lParam)!=0)
{
MessageBox("Failed to Get host by name!",NULL);
return;
}
PHOSTENT pHost=(PHOSTENT)m_host;
CEdit *pEdit=(CEdit*)GetDlgItem(IDC_EDIT1);
CString strHostAddr;
strHostAddr.Empty();
strHostAddr+="HostName:";
strHostAddr+=pHost->h_name;
strHostAddr+="\r\n";
int i=0;
strHostAddr+="Aliases:\r\n";
while (pHost->h_aliases[i]!=NULL)
{
strHostAddr+=pHost->h_aliases[i];
strHostAddr+="\r\n";
i++;
}
if (pHost->h_addrtype==AF_INET)
{
strHostAddr+="Address type:IPV4.\r\n";
}
else if(pHost->h_addrtype==AF_INET6)
{
strHostAddr+="Address type:IPV6\r\n";
}
else
{
strHostAddr+="UnKnown address type.\r\n";
}
if (pHost->h_length==4)
{
IN_ADDR inaddr;
for (int j=0;pHost->h_addr_list[j]!=NULL;j++)
{
inaddr.S_un.S_addr=(LONG)pHost->h_addr_list[j];
strHostAddr+=inet_ntoa(inaddr);
strHostAddr+="\r\n";
}
}
pEdit->SetWindowText(strHostAddr);
}
}
void CDemoDlg::OnButton1()
{
m_hGetHost=WSAAsyncGetHostByName(m_hWnd,WM_GETHOSTBYNAME,"www.tsinghua.edu.cn",m_host,MAXGETHOSTSTRUCT);
if(m_hGetHost==NULL)
{
CString strErr;
strErr.Format("Failed to Get host by name:%d\n",WSAGetLastError());
MessageBox(strErr,NULL,MB_OK|MB_ICONERROR);
}
}