malloc-h: New module.
[gnulib.git] / lib / xgethostname.c
blob36a88682b2835de3bb8481bb7bec33894e8ce172
1 /* xgethostname.c -- return current hostname with unlimited length
3 Copyright (C) 1992, 1996, 2000-2001, 2003-2006, 2009-2020 Free Software
4 Foundation, Inc.
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 3 of the License, or
9 (at your option) any later version.
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, see <https://www.gnu.org/licenses/>. */
19 /* written by Jim Meyering */
21 #include <config.h>
23 /* Specification. */
24 #include "xgethostname.h"
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <string.h>
29 #include <unistd.h>
31 #include "xalloc.h"
33 #ifndef INITIAL_HOSTNAME_LENGTH
34 # define INITIAL_HOSTNAME_LENGTH 34
35 #endif
37 /* Return the current hostname in malloc'd storage.
38 If malloc fails, exit.
39 Upon any other failure, return NULL and set errno. */
40 char *
41 xgethostname (void)
43 char *hostname = NULL;
44 size_t size = INITIAL_HOSTNAME_LENGTH;
46 while (1)
48 /* Use SIZE_1 here rather than SIZE to work around the bug in
49 SunOS 5.5's gethostname whereby it NUL-terminates HOSTNAME
50 even when the name is as long as the supplied buffer. */
51 size_t size_1;
53 hostname = x2realloc (hostname, &size);
54 size_1 = size - 1;
55 hostname[size_1 - 1] = '\0';
56 errno = 0;
58 if (gethostname (hostname, size_1) == 0)
60 if (! hostname[size_1 - 1])
61 break;
63 else if (errno != 0 && errno != ENAMETOOLONG && errno != EINVAL
64 /* OSX/Darwin does this when the buffer is not large enough */
65 && errno != ENOMEM)
67 int saved_errno = errno;
68 free (hostname);
69 errno = saved_errno;
70 return NULL;
74 /* Shrink HOSTNAME before returning it. */
76 size_t actual_size = strlen (hostname) + 1;
77 if (actual_size < size)
79 char *shrinked_hostname = realloc (hostname, actual_size);
80 if (shrinked_hostname != NULL)
81 hostname = shrinked_hostname;
85 return hostname;