Back to index

glibc  2.9
ifreq.c
Go to the documentation of this file.
00001 /* Copyright (C) 1999, 2002, 2003, 2004 Free Software Foundation, Inc.
00002    This file is part of the GNU C Library.
00003    Contributed by Andreas Jaeger <aj@suse.de>.
00004 
00005    The GNU C Library is free software; you can redistribute it and/or
00006    modify it under the terms of the GNU Lesser General Public
00007    License as published by the Free Software Foundation; either
00008    version 2.1 of the License, or (at your option) any later version.
00009 
00010    The GNU C Library is distributed in the hope that it will be useful,
00011    but WITHOUT ANY WARRANTY; without even the implied warranty of
00012    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013    Lesser General Public License for more details.
00014 
00015    You should have received a copy of the GNU Lesser General Public
00016    License along with the GNU C Library; if not, write to the Free
00017    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00018    02111-1307 USA.  */
00019 
00020 #include "ifreq.h"
00021 
00022 
00023 void
00024 __ifreq (struct ifreq **ifreqs, int *num_ifs, int sockfd)
00025 {
00026   int fd = sockfd;
00027   struct ifconf ifc;
00028   int rq_len;
00029   int nifs;
00030 # define RQ_IFS      4
00031 
00032   if (fd < 0)
00033     fd = __opensock ();
00034   if (fd < 0)
00035     {
00036       *num_ifs = 0;
00037       *ifreqs = NULL;
00038       return;
00039     }
00040 
00041   ifc.ifc_buf = NULL;
00042   rq_len = RQ_IFS * sizeof (struct ifreq) / 2; /* Doubled in the loop.  */
00043   do
00044     {
00045       ifc.ifc_len = rq_len *= 2;
00046       void *newp = realloc (ifc.ifc_buf, ifc.ifc_len);
00047       if (newp == NULL || __ioctl (fd, SIOCGIFCONF, &ifc) < 0)
00048        {
00049          free (ifc.ifc_buf);
00050 
00051          if (fd != sockfd)
00052            __close (fd);
00053          *num_ifs = 0;
00054          *ifreqs = NULL;
00055          return;
00056        }
00057       ifc.ifc_buf = newp;
00058     }
00059   while (rq_len < sizeof (struct ifreq) + ifc.ifc_len);
00060 
00061   if (fd != sockfd)
00062     __close (fd);
00063 
00064 #ifdef _HAVE_SA_LEN
00065   struct ifreq *ifr = *ifreqs;
00066   nifs = 0;
00067   while ((char *) ifr < ifc.ifc_buf + ifc.ifc_len)
00068     {
00069       ++nifs;
00070       ifr = __if_nextreq (ifr);
00071       if (ifr == NULL)
00072        break;
00073     }
00074 #else
00075   nifs = ifc.ifc_len / sizeof (struct ifreq);
00076 #endif
00077 
00078   *num_ifs = nifs;
00079   *ifreqs = realloc (ifc.ifc_buf, nifs * sizeof (struct ifreq));
00080 }