的原型gethostbyname_r
是:
int gethostbyname_r(const char *name,
struct hostent *ret, char *buf, size_t buflen,
struct hostent **result, int *h_errnop);
为了避免不可重入gethostbyname
,我写了这些东西:
int host2addr(const char *host, struct in_addr *addr) {
struct hostent he, *result;
int herr, ret, bufsz = 512;
char *buff = NULL;
do {
char *new_buff = (char *)realloc(buff, bufsz);
if (new_buff == NULL) {
free(buff);
return ENOMEM;
}
buff = new_buff;
ret = gethostbyname_r(host, &he, buff, bufsz, &result, &herr);
bufsz *= 2;
} while (ret == ERANGE);
if (ret == 0 && result != NULL)
*addr = *(struct in_addr *)he.h_addr;
else if (result != &he)
ret = herr;
free(buff);
return ret;
}
这与GNU 文档中的示例以及 eglibc-2.15 中的gethostname
.
但我注意到,有h_name
, h_aliases
,h_addr_list
在 a struct hostent
:
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
}
因此,我想知道释放这些指针所指的内容是否真的无关紧要。是否有其他机制处理这些记忆?