| 186 | } |
| 187 | |
| 188 | int hostname2ip(const char* hostname, ip_t* ip) { |
| 189 | char buf[256]; |
| 190 | if (NULL == hostname) { |
| 191 | if (gethostname(buf, sizeof(buf)) < 0) { |
| 192 | return -1; |
| 193 | } |
| 194 | hostname = buf; |
| 195 | } else { |
| 196 | // skip heading space |
| 197 | for (; isspace(*hostname); ++hostname); |
| 198 | } |
| 199 | |
| 200 | #if defined(OS_MACOSX) |
| 201 | // gethostbyname on MAC is thread-safe (with current usage) since the |
| 202 | // returned hostent is TLS. Check following link for the ref: |
| 203 | // https://lists.apple.com/archives/darwin-dev/2006/May/msg00008.html |
| 204 | struct hostent* result = gethostbyname(hostname); |
| 205 | if (result == NULL) { |
| 206 | return -1; |
| 207 | } |
| 208 | #else |
| 209 | int aux_buf_len = 1024; |
| 210 | std::unique_ptr<char[]> aux_buf(new char[aux_buf_len]); |
| 211 | int ret = 0; |
| 212 | int error = 0; |
| 213 | struct hostent ent; |
| 214 | struct hostent* result = NULL; |
| 215 | do { |
| 216 | result = NULL; |
| 217 | error = 0; |
| 218 | ret = gethostbyname_r(hostname, |
| 219 | &ent, |
| 220 | aux_buf.get(), |
| 221 | aux_buf_len, |
| 222 | &result, |
| 223 | &error); |
| 224 | if (ret != ERANGE) { // aux_buf is not long enough |
| 225 | break; |
| 226 | } |
| 227 | aux_buf_len *= 2; |
| 228 | aux_buf.reset(new char[aux_buf_len]); |
| 229 | } while (1); |
| 230 | if (ret != 0 || result == NULL) { |
| 231 | return -1; |
| 232 | } |
| 233 | #endif // defined(OS_MACOSX) |
| 234 | // Only fetch the first address here |
| 235 | bcopy((char*)result->h_addr, (char*)ip, result->h_length); |
| 236 | return 0; |
| 237 | } |
| 238 | |
| 239 | struct MyAddressInfo { |
| 240 | char my_hostname[256]; |
no test coverage detected