1、关于gethostbyname_r参数说明:
参数说明:name——是网页的host名称,如百度的host名是www.baidu.com
ret——成功的情况下存储结果用。
buf——这是一个临时的缓冲区,用来存储过程中的各种信息,一般8192大小就够了,可以申请一个数组char buf[8192]
buflen——是buf缓冲区的大小
result——如果成功,则这个hostent指针指向ret,也就是正确的结果;如果失败,则result为NULL
h_errnop——存储错误码
该函数成功返回0,失败返回一个非0的数。
struct hostent {
char *h_name; // official name of host
char **h_aliases; // alias list
int h_addrtype; // host address type——AF_INET || AF_INET6
int h_length; // length of address
char **h_addr_list; // list of addresses
};
#define h_addr h_addr_list[0] // for backward compatibility
2、关于gethostbyname_r的返回值
man手册是这么说的
/* GNU extensions */
struct hostent *gethostbyname2(const char *name, int af);
int gethostbyname_r (const char *name,
struct hostent *ret, char *buf, size_t buflen,
struct hostent **result, int *h_errnop);
int gethostbyname2_r (const char *name, int af,
struct hostent *ret, char *buf, size_t buflen,
struct hostent **result, int *h_errnop);
......
The functions gethostbyname() and gethostbyaddr() may return pointers
to static data, which may be overwritten by later calls. Copying the
struct hostent does not suffice, since it contains pointers - a deep
copy is required.
Glibc2 also has a gethostbyname2() that works like gethostbyname(),
but permits to specify the address family to which the address must
belong.
Glibc2 also has reentrant versions gethostbyname_r() and gethostby-
name2_r(). These return 0 on success and nonzero on error. The result
of the call is now stored in the struct with address ret. After the
call, *result will be NULL on error or point to the result on success.
Auxiliary data is stored in the buffer buf of length buflen. (If the
buffer is too small, these functions will return ERANGE.) No global
variable h_errno is modified, but the address of a variable in which
to store error numbers is passed in h_errnop.
按照man的说法
gethostbyname_r()调用成功时返回0
*result指向解析成功的数据结构, *result如果为NULL则表示解析出错
我根据实验发现
如果被解析的字符串是类似"xxx.xxx.xxx.xxx"的 数字+点 字符串
那么gethostbyname_r并没有发出DNS请求
而是直接去计算了
192.1468.80.38显然不是合法的IP地址, 但gethostbyname_r()返回0
此时*result是NULL
所以我程序中的那句ip4 = *(unsigned int *)(hostinfo.h_addr);就会段错误
如果被解析的字串确实无法解析, gethostbyname_r()返回非零值
但前提是: 这个字串不能是类似"xxx.xxx.xxx.xxx"的 数字+点 字符串
否则gethostbyname_r根本不发出DNS请求
刚才在FreeBSD/MAC OS X上测试了一下
对于192.1468.80.38这样的非法IP地址, gethostbyname_r()返回非零值,
不会导致执行ip4 = *(unsigned int *)(hostinfo.h_addr);造成段错误