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