LookUp.exe 的实现
原创yuprxk 最后发布于2014-05-08 12:09:42 阅读数 543 收藏
展开
d
#include <WinSock2.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int handle_error()
{
WSACleanup();
return EXIT_FAILURE;
}
int main(int __argc, char** __argv)
{
WSADATA wsa;
if (0 != WSAStartup(MAKEWORD(2,2), &wsa) )
{
cerr <<"WSAStartup() failed!" << endl;
return handle_error();
}
PHOSTENT pHostEnt = NULL;
IN_ADDR addr;
if (__argc == 2)
{
if (__argv[1] && isdigit(*__argv[1]) ) //参数2,也就是地址或主机名有效,且包含数字,则以IP地址处理
{
addr.s_addr = inet_addr(__argv[1] ) ; //ip地址
if (INADDR_NONE == addr.s_addr)
{
cerr << __argv[1] << " invalid addr!" << endl;
return handle_error();
}
pHostEnt = gethostbyaddr((const char*)&addr, sizeof(sockaddr), AF_INET);
}
else
{
pHostEnt = gethostbyname(__argv[1]);
}
}
else
{
cout << "input like: \n\t lookup.exe www.sina.com \n\t lookup.exe 127.0.0.1"<<endl;
return handle_error();
}
if (NULL == pHostEnt )
{
cerr << "LookUp error:" << WSAGetLastError() << endl;
return handle_error();
}
cout << "official name:" << pHostEnt->h_name << endl;
if (*pHostEnt->h_aliases)
{
cout << "aliases:" << endl;
for (char** list = pHostEnt->h_aliases; *list != NULL; list++)
{
cout <<"\t"<< *list << endl;
}
}
switch (pHostEnt->h_addrtype)
{
case AF_INET:
cout << "AF_INET" ;
break;
case AF_INET6:
cout << "AF_INET6" ;
break;
default:
cout << "Unknown type!" ;
break;
}
cout << ", Type-Length:" << pHostEnt->h_length << endl;
cout << "addr_list:" << endl;
for (char** list = pHostEnt->h_addr_list; *list != NULL; list++)
{
memcpy(&addr.s_addr, list, pHostEnt->h_length);
cout <<"\t"<< inet_ntoa(addr)<<endl;
}
//清理资源
WSACleanup();
return EXIT_SUCCESS;
}
执行结果:
>lookup.exe www.sina.com
official name:polaris.sina.com.cn
aliases:
www.sina.com
us.sina.com.cn
news.sina.com.cn
jupiter.sina.com.cn
AF_INET, Type-Length:4
addr_list:
236.244.14.0
>lookup.exe 127.0.0.1
official name:zeek-PC
AF_INET, Type-Length:4
addr_list:
236.240.32.0
————————————————
版权声明:本文为CSDN博主「yuprxk」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yuprxk/article/details/25294935