SYNOPSIS
#include <netdb.h> struct hostent *gethostbyname(const char *name);
Data Structure
http://www.cnblogs.com/LubinLew/p/POSIX-DataStructure.html#struct_hostent
Description
gethostbyname 是不可重入函數,在多線程編程時需要注意, linux中有可重入版本 gethostbyname_r,
POSIX標准里面使用getaddrinfo和getnameinfo來替換gethostbyname系列函數了,這些函數已經已經被廢棄了。
Parameter
參數 name 既可以是一個主機名(例如"www.163.com"),也可以是IPv4地址(點分十進制形式,例如"111.202.60.48")或者IPv6地址(冒號分隔16進制地址.例如"2000::1:2345:6789:abcd").
如果參數是IPv4或者IPv6地址,那么函數不會執行查詢操作,返回的結構體中 h_name 就是該參數的拷貝, h_addr_list[0]就是該參數對應的的整型網絡字節(相當於inet_pton(AF_INET*, name, dst)).
If name doesn’t end in a dot and the environment variable HOSTALIASES is set, the alias file pointed to by HOSTALIASES will first be searched for name (see hostname(7) for the file format).
The current domain and its parents are searched unless name ends in a dot.
Example
#include <stdio.h> #include <netdb.h> #include <arpa/inet.h> int main(void) { int i = 0; char str[32] = {0}; struct hostent* phost = NULL; phost = gethostbyname("www.163.com"); if (NULL == phost) { return -1; } printf("---Offical name:\n\t%s\n", phost->h_name); printf("---Alias name:\n"); for (i = 0; phost->h_aliases[i]; i++) { printf("\t%s\n", phost->h_aliases[i]); } printf("---Address list:\n"); for (i = 0; phost->h_addr_list[i]; i++) { printf("\t%s\n", inet_ntop(phost->h_addrtype, phost->h_addr_list[i], str, sizeof(str)-1)); } return 0; }
運行結果
---Offical name: 163.xdwscache.glb0.lxdns.com ---Alias name: www.163.com www.163.com.lxdns.com ---Address list: 111.202.60.48 111.202.60.47