1.gethostbyname
gethostbyname()可以根据主机的域名得到相关的信息,它返回一个指向hostent类型的指针。gostent结构体定义如下:
struct hostent
{
char *h_name;
char **h_aliases;
int h_addrtype;
int h_length;
char **h_addr_list;
};
hostent->h_name
表示的是主机的规范名。例如www.google.com的规范名其实是www.l.google.com。
hostent->h_aliases
表示的是主机的别名.www.google.com就是google他自己的别名。有的时候,有的主机可能有好几个别名,这些,其实都是为了易于用户记忆而为自己的网站多取的名字。
hostent->h_addrtype
表示的是主机ip地址的类型,到底是ipv4(AF_INET),还是pv6(AF_INET6)
hostent->h_length
表示的是主机ip地址的长度
hostent->h_addr_list
表示主机的ip地址列表,是字符串类型的网络字节地址,需要先转成u_long,再进行打印
比如解析百度的地址:
// test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdio.h>
#include "winsock2.h"
#include <stdlib.h>
#pragma comment(lib,"ws2_32.lib")
int main()
{
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
SOCKET s;
hostent *phost;
char *pstr;
phost = gethostbyname("www.baidu.com");
printf("offical name: %s\n", phost->h_name);
int i = 0;
for (pstr = phost->h_aliases[i]; pstr != NULL; pstr = phost->h_aliases[++i])
{
printf("alias: %s\n", pstr);
}
if (phost->h_addrtype == AF_INET)
{
printf("address type: ipv4\n");
}
else if (phost->h_addrtype == AF_INET6)
{
printf("address type: ipv6\n");
}
i = 0;
for (pstr = phost->h_addr_list[0]; pstr != NULL; pstr = phost->h_addr_list[++i])
{
u_long temp;
temp = *(u_long*)pstr;
in_addr in;
in.S_un.S_addr = temp;
printf("%s\n", inet_ntoa(in));
}
WSACleanup();
return 0;
}