gethostbyaddr_r.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 <inttypes.h>
  8. int gethostbyaddr_r(const void *a, socklen_t l, int af,
  9. struct hostent *h, char *buf, size_t buflen,
  10. struct hostent **res, int *err)
  11. {
  12. union {
  13. struct sockaddr_in sin;
  14. struct sockaddr_in6 sin6;
  15. } sa = { .sin.sin_family = af };
  16. socklen_t sl = af==AF_INET6 ? sizeof sa.sin6 : sizeof sa.sin;
  17. int i;
  18. /* Load address argument into sockaddr structure */
  19. if (af==AF_INET6 && l==16) memcpy(&sa.sin6.sin6_addr, a, 16);
  20. else if (af==AF_INET && l==4) memcpy(&sa.sin.sin_addr, a, 4);
  21. else {
  22. *err = NO_RECOVERY;
  23. return EINVAL;
  24. }
  25. /* Align buffer and check for space for pointers and ip address */
  26. i = (uintptr_t)buf & sizeof(char *)-1;
  27. if (!i) i = sizeof(char *);
  28. if (buflen <= 5*sizeof(char *)-i + l) return ERANGE;
  29. buf += sizeof(char *)-i;
  30. buflen -= 5*sizeof(char *)-i + l;
  31. h->h_addr_list = (void *)buf;
  32. buf += 2*sizeof(char *);
  33. h->h_aliases = (void *)buf;
  34. buf += 2*sizeof(char *);
  35. h->h_addr_list[0] = buf;
  36. memcpy(h->h_addr_list[0], a, l);
  37. buf += l;
  38. h->h_addr_list[1] = 0;
  39. h->h_aliases[0] = buf;
  40. h->h_aliases[1] = 0;
  41. switch (getnameinfo((void *)&sa, sl, buf, buflen, 0, 0, 0)) {
  42. case EAI_AGAIN:
  43. *err = TRY_AGAIN;
  44. return EAGAIN;
  45. case EAI_OVERFLOW:
  46. return ERANGE;
  47. default:
  48. case EAI_MEMORY:
  49. case EAI_SYSTEM:
  50. case EAI_FAIL:
  51. *err = NO_RECOVERY;
  52. return errno;
  53. case 0:
  54. break;
  55. }
  56. h->h_addrtype = af;
  57. h->h_name = h->h_aliases[0];
  58. *res = h;
  59. return 0;
  60. }