ifreq.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. /* We may be able to get the needed buffer size directly, rather than
  34. guessing. */
  35. ifc.ifc_buf = NULL;
  36. ifc.ifc_len = 0;
  37. if (__ioctl (fd, SIOCGIFCONF, &ifc) < 0 || ifc.ifc_len == 0)
  38. rq_len = RQ_IFS * sizeof (struct ifreq);
  39. else
  40. rq_len = ifc.ifc_len;
  41. /* Read all the interfaces out of the kernel. */
  42. ifc.ifc_len = rq_len;
  43. void *newp = realloc (ifc.ifc_buf, ifc.ifc_len);
  44. if (newp == NULL
  45. || (ifc.ifc_buf = newp, __ioctl (fd, SIOCGIFCONF, &ifc)) < 0)
  46. {
  47. free (ifc.ifc_buf);
  48. if (fd != sockfd)
  49. __close (fd);
  50. *num_ifs = 0;
  51. *ifreqs = NULL;
  52. return;
  53. }
  54. nifs = ifc.ifc_len / sizeof (struct ifreq);
  55. if (fd != sockfd)
  56. __close (fd);
  57. *num_ifs = nifs;
  58. *ifreqs = realloc (ifc.ifc_buf, nifs * sizeof (struct ifreq));
  59. }