rpc_gethostbyname.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* IPv4-only variant of gethostbyname.
  2. Copyright (C) 2016-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public License as
  6. published by the Free Software Foundation; either version 2.1 of the
  7. License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; see the file COPYING.LIB. If
  14. not, see <http://www.gnu.org/licenses/>. */
  15. #include <errno.h>
  16. #include <netdb.h>
  17. #include <rpc/rpc.h>
  18. #include <scratch_buffer.h>
  19. #include <string.h>
  20. int
  21. __libc_rpc_gethostbyname (const char *host, struct sockaddr_in *addr)
  22. {
  23. struct hostent hostbuf;
  24. struct hostent *hp = NULL;
  25. int herr;
  26. struct scratch_buffer tmpbuf;
  27. scratch_buffer_init (&tmpbuf);
  28. while (__gethostbyname2_r (host, AF_INET,
  29. &hostbuf, tmpbuf.data, tmpbuf.length, &hp,
  30. &herr) != 0
  31. || hp == NULL)
  32. if (herr != NETDB_INTERNAL || errno != ERANGE)
  33. {
  34. struct rpc_createerr *ce = &get_rpc_createerr ();
  35. ce->cf_stat = RPC_UNKNOWNHOST;
  36. scratch_buffer_free (&tmpbuf);
  37. return -1;
  38. }
  39. else
  40. {
  41. if (!scratch_buffer_grow (&tmpbuf))
  42. {
  43. /* If memory allocation failed, allocating the RPC error
  44. structure might could as well, so this could lead to a
  45. crash. */
  46. struct rpc_createerr *ce = &get_rpc_createerr ();
  47. ce->cf_stat = RPC_SYSTEMERROR;
  48. ce->cf_error.re_errno = ENOMEM;
  49. return -1;
  50. }
  51. }
  52. if (hp->h_addrtype != AF_INET || hp->h_length != sizeof (addr->sin_addr))
  53. {
  54. struct rpc_createerr *ce = &get_rpc_createerr ();
  55. ce->cf_stat = RPC_SYSTEMERROR;
  56. ce->cf_error.re_errno = EAFNOSUPPORT;
  57. scratch_buffer_free (&tmpbuf);
  58. return -1;
  59. }
  60. addr->sin_family = AF_INET;
  61. addr->sin_port = htons (0);
  62. memcpy (&addr->sin_addr, hp->h_addr, sizeof (addr->sin_addr));
  63. scratch_buffer_free (&tmpbuf);
  64. return 0;
  65. }