一、所用API函数介绍
struct hostent FAR*gethostbyname( const char FAR* name );
传入參数:const char FAR* name。主机名或者域名
返回值:一个指向struct hostent的指针
结构体hostent定义例如以下:
struct hostent {
char FAR * h_name;
char FAR * FAR * h_aliases;
short h_addrtype;
short h_length;
char FAR * FAR * h_addr_list;
};
结构体hostent成员介绍:
h_name:官方的主机名称,比方www.baidu.com的是www.a.shifen.com。
MSDN上的:If using the DNS or similar resolution system, it is the Fully Qualified Domain Name
(FQDN) that caused the server to return a reply. If using a local hosts file, it is the first entry after
the IP address.
h_aliases:主机别名、备用名。这是一个二级指针(别名可能会有多个,便于用户使用)
h_addrtype:地址类型,比方有IPV4、IPV6等。其在winsock.h文件里相应的宏为AF_INET与AF_INET6
h_length:地址长度,以字节为单位,如:IPV4的为4。IPV6的为16等
h_addr_list:主机的地址列表,即主机的IP地址列表,也是一个二级指针(可能会有多个,一个域名能够绑定多个ip。比方解析谷歌的,会输出74.125.23.99,74.125.23.147,74.125.23.105等等)。注意此处返回的地址是网络字节序的。所以须要进行一下转换,详细可看后面代码部分。
二、程序代码实现(在windows平台下)
#include <Winsock2.h> #include <ws2tcpip.h> #include <iostream> using namespace std; #pragma comment(lib, "Ws2_32.lib") int main() { //使用Ws2_32.dll的初始化 WORD wVersionRequested = 0; WSADATA wsaData = {}; int err = 0; wVersionRequested = MAKEWORD( 2, 2 ); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { return -1; } if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) { WSACleanup( ); return -1; } ////////////////////////// char** pptr = NULL; char szHostName[256] = {}; cout << "--------------------------------------" << endl; cout << "输入域名:"; while( cin.getline( szHostName, sizeof(szHostName) ) ) { HOSTENT* pHostEntry = gethostbyname( szHostName ); if( NULL != pHostEntry && szHostName[0] != '\0' ) { //将主机的规范名输出 cout << "主机规范名:" << pHostEntry->h_name << endl; //主机别名。可含多个 int i = 0; for ( i = 1, pptr = pHostEntry->h_aliases; *pptr != NULL; ++pptr ) { cout << "主机别名" << i++ << ":" << *pptr << endl; } //将主机地址列表输出,可含多个 char szIpBuff[32] = {0}; for ( i = 1, pptr = pHostEntry->h_addr_list; *pptr != NULL; ++pptr ) { memset( szIpBuff, 0, sizeof(szIpBuff) ); //inet_ntop的返回值为NULL,则表示失败。否则返回对应的IP地址(此时szIpRet指向的是szIpBuff) const char* szIpRet = inet_ntop( pHostEntry->h_addrtype, *pptr, szIpBuff, sizeof(szIpBuff) ); if ( szIpBuff != NULL ) { cout << "解析IP地址" << i++ << ":" << szIpRet << endl; } } } else { cout << "解析失败。" << endl; } memset( szHostName, 0, sizeof(szHostName) ); cout << "--------------------------------------" << endl; cout << "输入域名:"; } WSACleanup(); return 0; }
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvczYzNDc3MjIwOA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" >
作者:山丘儿
转载请标明出处,谢谢。原文地址:http://blog.csdn.net/s634772208/article/details/46378223