gethostbyname2_r.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 ENOENT;
  23. case EAI_AGAIN:
  24. *err = TRY_AGAIN;
  25. return EAGAIN;
  26. default:
  27. case EAI_FAIL:
  28. *err = NO_RECOVERY;
  29. return EBADMSG;
  30. case EAI_MEMORY:
  31. case EAI_SYSTEM:
  32. *err = NO_RECOVERY;
  33. return errno;
  34. }
  35. h->h_addrtype = af;
  36. h->h_length = af==AF_INET6 ? 16 : 4;
  37. /* Align buffer */
  38. align = -(uintptr_t)buf & sizeof(char *)-1;
  39. need = 4*sizeof(char *);
  40. need += (cnt + 1) * (sizeof(char *) + h->h_length);
  41. need += strlen(name)+1;
  42. need += strlen(canon)+1;
  43. need += align;
  44. if (need > buflen) return ERANGE;
  45. buf += align;
  46. h->h_aliases = (void *)buf;
  47. buf += 3*sizeof(char *);
  48. h->h_addr_list = (void *)buf;
  49. buf += (cnt+1)*sizeof(char *);
  50. for (i=0; i<cnt; i++) {
  51. h->h_addr_list[i] = (void *)buf;
  52. buf += h->h_length;
  53. memcpy(h->h_addr_list[i], addrs[i].addr, h->h_length);
  54. }
  55. h->h_addr_list[i] = 0;
  56. h->h_name = h->h_aliases[0] = buf;
  57. strcpy(h->h_name, canon);
  58. buf += strlen(h->h_name)+1;
  59. if (strcmp(h->h_name, name)) {
  60. h->h_aliases[1] = buf;
  61. strcpy(h->h_aliases[1], name);
  62. buf += strlen(h->h_aliases[1])+1;
  63. } else h->h_aliases[1] = 0;
  64. h->h_aliases[2] = 0;
  65. *res = h;
  66. return 0;
  67. }