1 /* xgethostname.c -- return current hostname with unlimited length
3 Copyright (C) 1992, 1996, 2000, 2001, 2003, 2004, 2005 Free Software
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)
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.
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. */
20 /* written by Jim Meyering */
27 #include "xgethostname.h"
39 # define ENAMETOOLONG 0
42 #ifndef INITIAL_HOSTNAME_LENGTH
43 # define INITIAL_HOSTNAME_LENGTH 34
46 /* Return the current hostname in malloc'd storage.
47 If malloc fails, exit.
48 Upon any other failure, return NULL and set errno. */
52 char *hostname
= NULL
;
53 size_t size
= INITIAL_HOSTNAME_LENGTH
;
57 /* Use SIZE_1 here rather than SIZE to work around the bug in
58 SunOS 5.5's gethostname whereby it NUL-terminates HOSTNAME
59 even when the name is as long as the supplied buffer. */
62 hostname
= x2realloc (hostname
, &size
);
64 hostname
[size_1
- 1] = '\0';
67 if (gethostname (hostname
, size_1
) == 0)
69 if (! hostname
[size_1
- 1])
72 else if (errno
!= 0 && errno
!= ENAMETOOLONG
&& errno
!= EINVAL
73 /* OSX/Darwin does this when the buffer is not large enough */
76 int saved_errno
= errno
;