Tizen 2.0 Release
[external/tizen-coreutils.git] / lib / xgethostname.c
1 /* xgethostname.c -- return current hostname with unlimited length
2
3    Copyright (C) 1992, 1996, 2000, 2001, 2003, 2004, 2005, 2006 Free
4    Software 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
19
20 /* written by Jim Meyering */
21
22 #include <config.h>
23
24 /* Specification.  */
25 #include "xgethostname.h"
26
27 #include <stdlib.h>
28 #include <errno.h>
29 #include <unistd.h>
30
31 #include "xalloc.h"
32
33 #ifndef ENAMETOOLONG
34 # define ENAMETOOLONG 0
35 #endif
36
37 #ifndef INITIAL_HOSTNAME_LENGTH
38 # define INITIAL_HOSTNAME_LENGTH 34
39 #endif
40
41 /* Return the current hostname in malloc'd storage.
42    If malloc fails, exit.
43    Upon any other failure, return NULL and set errno.  */
44 char *
45 xgethostname (void)
46 {
47   char *hostname = NULL;
48   size_t size = INITIAL_HOSTNAME_LENGTH;
49
50   while (1)
51     {
52       /* Use SIZE_1 here rather than SIZE to work around the bug in
53          SunOS 5.5's gethostname whereby it NUL-terminates HOSTNAME
54          even when the name is as long as the supplied buffer.  */
55       size_t size_1;
56
57       hostname = x2realloc (hostname, &size);
58       size_1 = size - 1;
59       hostname[size_1 - 1] = '\0';
60       errno = 0;
61
62       if (gethostname (hostname, size_1) == 0)
63         {
64           if (! hostname[size_1 - 1])
65             break;
66         }
67       else if (errno != 0 && errno != ENAMETOOLONG && errno != EINVAL
68                /* OSX/Darwin does this when the buffer is not large enough */
69                && errno != ENOMEM)
70         {
71           int saved_errno = errno;
72           free (hostname);
73           errno = saved_errno;
74           return NULL;
75         }
76     }
77
78   return hostname;
79 }