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;}
新聞熱點
疑難解答