轉載:http://www.cnblogs.com/cxz2009/archive/2010/11/19/1881611.html
gethostbyname()函數說明——用域名或主機名獲取IP地址
?? ?包含頭文件
??? #include <netdb.h>
??? #include <sys/socket.h>
?? ?函數原型
??? struct hostent *gethostbyname(const char *name);
??? 這個函數的傳入值是域名或者主機名,例如"www.google.cn"等等。傳出值,是一個hostent的結構。如果函數調用失敗,將返回NULL。
?? ?返回hostent結構體類型指針
??? struct hostent
??? {
??????? char??? *h_name;????????????? ?
??????? char??? **h_aliases;
??????? int???? h_addrtype;
??????? int???? h_length;
??????? char??? **h_addr_list;
??????? #define h_addr h_addr_list[0]
??? };
??? 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_lisst
??? 表示的是主機的ip地址,注意,這個是以網絡字節序存儲的。千萬不要直接用printf帶%s參數來打這個東西,會有問題的哇。所以到真正需要打印出這個IP的話,需要調用inet_ntop()。
??? const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) :
??? 這個函數,是將類型為af的網絡地址結構src,轉換成主機序的字符串形式,存放在長度為cnt的字符串中。返回指向dst的一個指針。如果函數調用錯誤,返回值是NULL。

?2?#include?<sys/socket.h>
?3?#include?<stdio.h>
?4?
?5?int?main(int?argc,?char?**argv)
?6?{
?7?????char???*ptr,?**pptr;
?8?????struct?hostent?*hptr;
?9?????char???str[32];
10?????ptr?=?argv[1];
11?
12?????if((hptr?=?gethostbyname(ptr))?==?NULL)
13?????{
14?????????printf("?gethostbyname?error?for?host:%s\n",?ptr);
15?????????return?0;
16?????}
17?
18?????printf("official?hostname:%s\n",hptr->h_name);
19?????for(pptr?=?hptr->h_aliases;?*pptr?!=?NULL;?pptr++)
20?????????printf("?alias:%s\n",*pptr);
21?
22?????switch(hptr->h_addrtype)
23?????{
24?????????case?AF_INET:
25?????????case?AF_INET6:
26?????????????pptr=hptr->h_addr_list;
27?????????????for(;?*pptr!=NULL;?pptr++)
28?????????????????printf("?address:%s\n",
29????????????????????????inet_ntop(hptr->h_addrtype,?*pptr,?str,?sizeof(str)));
30?????????????printf("?first?address:?%s\n",
31????????????????????????inet_ntop(hptr->h_addrtype,?hptr->h_addr,?str,?sizeof(str)));
32?????????break;
33?????????default:
34?????????????printf("unknown?address?type\n");
35?????????break;
36?????}
37?
38?????return?0;
39?}
編譯運行
-----------------------------
# gcc test.c
# ./a.out www.baidu.com
official hostname:www.a.shifen.com
alias:www.baidu.com
address:121.14.88.11
address:121.14.89.11
first address: 121.14.88.11
?