home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 22 gnu / 22-gnu.zip / gnunet10.zip / source / libinetutils / localhost.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-07-27  |  2.1 KB  |  80 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. #include <unistd.h>
  22. #include <malloc.h>
  23. #include <string.h>
  24. #include <errno.h>
  25. #ifdef __EMX__
  26. # include <stdlib.h>
  27. #endif
  28.  
  29. /* Return the name of the localhost.  This is just a wrapper for gethostname,
  30.    which takes care of allocating a big enough buffer, and caches the result
  31.    after the first call (so the result should be copied before modification).
  32.    If something goes wrong, 0 is returned, and errno set.  */
  33. char *
  34. localhost ()
  35. {
  36.   static char *buf = 0;
  37.   static size_t buf_len = 0;
  38.  
  39.   if (! buf)
  40.     {
  41.       do {
  42.     errno = 0;
  43.  
  44.     if (buf) {
  45.       buf_len += buf_len;
  46.       buf = realloc (buf, buf_len);
  47.     } else {
  48.       buf_len = 128;    /* Initial guess */
  49.       buf = malloc (buf_len);
  50.     }
  51.  
  52.     if (! buf)
  53.       {
  54.         errno = ENOMEM;
  55.         return 0;
  56.       }
  57.       } while ((gethostname(buf, buf_len) == 0 && !memchr (buf, '\0', buf_len))
  58.            || errno == ENAMETOOLONG);
  59.  
  60.       if (errno)
  61.     /* gethostname failed, abort.  */
  62.     {
  63.       free (buf);
  64.       buf = 0;
  65.     }
  66.     }
  67.  
  68.   return buf;
  69. }
  70.  
  71. #ifdef __EMX__
  72. int gethostname(char *buf,int buf_len)
  73. {
  74.     char *ptr=getenv("HOSTNAME");
  75.     if (!ptr) return 1; /* HOST_NOT_FOUND from netdb.h */
  76.     strncpy(buf,ptr,buf_len);
  77.     return 0;
  78. }
  79. #endif /* __EMX__ */
  80.