Correct SunOS and Solaris version number notation to match Sun's usage.
[gnulib.git] / lib / xgethostname.c
1 /* xgethostname.c -- return current hostname with unlimited length
2    Copyright (C) 1992, 1996, 2000, 2001, 2003 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* written by Jim Meyering */
19
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #include <sys/types.h>
25
26 #include <errno.h>
27 #ifndef errno
28 extern int errno;
29 #endif
30
31 #include "error.h"
32 #include "xalloc.h"
33
34 #ifndef ENAMETOOLONG
35 # define ENAMETOOLONG 9999
36 #endif
37
38 #ifndef EXIT_FAILURE
39 # define EXIT_FAILURE 1
40 #endif
41
42 int gethostname ();
43
44 #ifndef INITIAL_HOSTNAME_LENGTH
45 # define INITIAL_HOSTNAME_LENGTH 34
46 #endif
47
48 char *
49 xgethostname ()
50 {
51   char *hostname;
52   size_t size;
53
54   size = INITIAL_HOSTNAME_LENGTH;
55   /* Use size + 1 here rather than size to work around the bug
56      in SunOS 5.5's gethostname whereby it NUL-terminates HOSTNAME
57      even when the name is longer than the supplied buffer.  */
58   hostname = xmalloc (size + 1);
59   while (1)
60     {
61       int k = size - 1;
62       int err;
63
64       errno = 0;
65       hostname[k] = '\0';
66       err = gethostname (hostname, size);
67       if (err >= 0 && hostname[k] == '\0')
68         break;
69       else if (err < 0 && errno != ENAMETOOLONG && errno != 0)
70         error (EXIT_FAILURE, errno, "gethostname");
71       size *= 2;
72       hostname = xrealloc (hostname, size + 1);
73     }
74
75   return hostname;
76 }