1
0

gethostbyname2_r.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #define _GNU_SOURCE
  2. #include <sys/socket.h>
  3. #include <netdb.h>
  4. #include <string.h>
  5. #include <netinet/in.h>
  6. #include <errno.h>
  7. #include <stdint.h>
  8. #include "lookup.h"
  9. int gethostbyname2_r(const char *name, int af,
  10. struct hostent *h, char *buf, size_t buflen,
  11. struct hostent **res, int *err)
  12. {
  13. struct address addrs[MAXADDRS];
  14. char canon[256];
  15. int i, cnt;
  16. size_t align, need;
  17. *res = 0;
  18. cnt = __lookup_name(addrs, canon, name, af, AI_CANONNAME);
  19. if (cnt<0) switch (cnt) {
  20. case EAI_NONAME:
  21. *err = HOST_NOT_FOUND;
  22. return 0;
  23. case EAI_NODATA:
  24. *err = NO_DATA;
  25. return 0;
  26. case EAI_AGAIN:
  27. *err = TRY_AGAIN;
  28. return EAGAIN;
  29. default:
  30. case EAI_FAIL:
  31. *err = NO_RECOVERY;
  32. return EBADMSG;
  33. case EAI_SYSTEM:
  34. *err = NO_RECOVERY;
  35. return errno;
  36. }
  37. h->h_addrtype = af;
  38. h->h_length = af==AF_INET6 ? 16 : 4;
  39. /* Align buffer */
  40. align = -(uintptr_t)buf & sizeof(char *)-1;
  41. need = 4*sizeof(char *);
  42. need += (cnt + 1) * (sizeof(char *) + h->h_length);
  43. need += strlen(name)+1;
  44. need += strlen(canon)+1;
  45. need += align;
  46. if (need > buflen) return ERANGE;
  47. buf += align;
  48. h->h_aliases = (void *)buf;
  49. buf += 3*sizeof(char *);
  50. h->h_addr_list = (void *)buf;
  51. buf += (cnt+1)*sizeof(char *);
  52. for (i=0; i<cnt; i++) {
  53. h->h_addr_list[i] = (void *)buf;
  54. buf += h->h_length;
  55. memcpy(h->h_addr_list[i], addrs[i].addr, h->h_length);
  56. }
  57. h->h_addr_list[i] = 0;
  58. h->h_name = h->h_aliases[0] = buf;
  59. strcpy(h->h_name, canon);
  60. buf += strlen(h->h_name)+1;
  61. if (strcmp(h->h_name, name)) {
  62. h->h_aliases[1] = buf;
  63. strcpy(h->h_aliases[1], name);
  64. buf += strlen(h->h_aliases[1])+1;
  65. } else h->h_aliases[1] = 0;
  66. h->h_aliases[2] = 0;
  67. *res = h;
  68. return 0;
  69. }