home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / inetutils-1.2-src.tgz / tar.out / fsf / inetutils / libinetutils / localhost.c < prev    next >
C/C++ Source or Header  |  1996-09-28  |  2KB  |  71 lines

  1. /* A slightly more convenient wrapper for gethostname
  2.  
  3.    Copyright (C) 1996 Free Software Foundation, Inc.
  4.  
  5.    Written by Miles Bader <miles@gnu.ai.mit.edu>
  6.  
  7.    This program is free software; you can redistribute it and/or
  8.    modify it under the terms of the GNU General Public License as
  9.    published by the Free Software Foundation; either version 2, or (at
  10.    your option) any later version.
  11.  
  12.    This program is distributed in the hope that it will be useful, but
  13.    WITHOUT ANY WARRANTY; without even the implied warranty of
  14.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15.    General Public License for more details.
  16.  
  17.    You should have received a copy of the GNU General Public License
  18.    along with this program; if not, write to the Free Software
  19.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  20.  
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24.  
  25. #include <unistd.h>
  26. #include <malloc.h>
  27. #include <string.h>
  28. #include <errno.h>
  29.  
  30. /* Return the name of the localhost.  This is just a wrapper for gethostname,
  31.    which takes care of allocating a big enough buffer, and caches the result
  32.    after the first call (so the result should be copied before modification).
  33.    If something goes wrong, 0 is returned, and errno set.  */
  34. char *
  35. localhost ()
  36. {
  37.   static char *buf = 0;
  38.   static size_t buf_len = 0;
  39.  
  40.   if (! buf)
  41.     {
  42.       do {
  43.     errno = 0;
  44.  
  45.     if (buf) {
  46.       buf_len += buf_len;
  47.       buf = realloc (buf, buf_len);
  48.     } else {
  49.       buf_len = 128;    /* Initial guess */
  50.       buf = malloc (buf_len);
  51.     }
  52.  
  53.     if (! buf)
  54.       {
  55.         errno = ENOMEM;
  56.         return 0;
  57.       }
  58.       } while ((gethostname(buf, buf_len) == 0 && !memchr (buf, '\0', buf_len))
  59.            || errno == ENAMETOOLONG);
  60.  
  61.       if (errno)
  62.     /* gethostname failed, abort.  */
  63.     {
  64.       free (buf);
  65.       buf = 0;
  66.     }
  67.     }
  68.  
  69.   return buf;
  70. }
  71.