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官方文檔里的例子一致(GNU的還少了個free的樣子)。 但是對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 */ } #define h_addr h_addr_list[0] /* for backward compatibility */ 這里面有h_name,h_aliases,h_addr_list ... 我又翻看了下eglibc-2.15的gethostbyname的源碼,邏輯基本上跟我上面這段一樣。但是,這些東西沒釋放的話,真的沒問題嗎? |
|