ifreq.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* Copyright (C) 1999-2019 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. Contributed by Andreas Jaeger <aj@suse.de>.
  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
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the 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; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include "ifreq.h"
  16. void
  17. __ifreq (struct ifreq **ifreqs, int *num_ifs, int sockfd)
  18. {
  19. int fd = sockfd;
  20. struct ifconf ifc;
  21. int rq_len;
  22. int nifs;
  23. # define RQ_IFS 4
  24. if (fd < 0)
  25. fd = __opensock ();
  26. if (fd < 0)
  27. {
  28. *num_ifs = 0;
  29. *ifreqs = NULL;
  30. return;
  31. }
  32. ifc.ifc_buf = NULL;
  33. rq_len = RQ_IFS * sizeof (struct ifreq) / 2; /* Doubled in the loop. */
  34. do
  35. {
  36. ifc.ifc_len = rq_len *= 2;
  37. void *newp = realloc (ifc.ifc_buf, ifc.ifc_len);
  38. if (newp == NULL || __ioctl (fd, SIOCGIFCONF, &ifc) < 0)
  39. {
  40. free (ifc.ifc_buf);
  41. if (fd != sockfd)
  42. __close (fd);
  43. *num_ifs = 0;
  44. *ifreqs = NULL;
  45. return;
  46. }
  47. ifc.ifc_buf = newp;
  48. }
  49. while (rq_len < sizeof (struct ifreq) + ifc.ifc_len);
  50. if (fd != sockfd)
  51. __close (fd);
  52. #ifdef _HAVE_SA_LEN
  53. struct ifreq *ifr = *ifreqs;
  54. nifs = 0;
  55. while ((char *) ifr < ifc.ifc_buf + ifc.ifc_len)
  56. {
  57. ++nifs;
  58. ifr = __if_nextreq (ifr);
  59. if (ifr == NULL)
  60. break;
  61. }
  62. #else
  63. nifs = ifc.ifc_len / sizeof (struct ifreq);
  64. #endif
  65. *num_ifs = nifs;
  66. *ifreqs = realloc (ifc.ifc_buf, nifs * sizeof (struct ifreq));
  67. }