.
[coreutils.git] / lib / xgethostname.c
blob1f4d728a038210f0805b0a0b02891f24dc0b9c9d
1 /* xgethostname.c -- return current hostname with unlimited length
2 Copyright (C) 1992, 1996, 2000, 2001, 2003 Free Software Foundation, Inc.
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.
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.
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. */
18 /* written by Jim Meyering */
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
24 /* Specification. */
25 #include "xgethostname.h"
27 #include <stdlib.h>
28 #include <sys/types.h>
30 #include <errno.h>
31 #ifndef errno
32 extern int errno;
33 #endif
35 #include "error.h"
36 #include "exit.h"
37 #include "xalloc.h"
39 #ifndef ENAMETOOLONG
40 # define ENAMETOOLONG 9999
41 #endif
43 int gethostname ();
45 #ifndef INITIAL_HOSTNAME_LENGTH
46 # define INITIAL_HOSTNAME_LENGTH 34
47 #endif
49 /* Return the current hostname in malloc'd storage.
50 If malloc fails, exit.
51 Upon any other failure, return NULL. */
52 char *
53 xgethostname (void)
55 char *hostname;
56 size_t size;
58 size = INITIAL_HOSTNAME_LENGTH;
59 /* Use size + 1 here rather than size to work around the bug
60 in SunOS 5.5's gethostname whereby it NUL-terminates HOSTNAME
61 even when the name is longer than the supplied buffer. */
62 hostname = xmalloc (size + 1);
63 while (1)
65 int k = size - 1;
66 int err;
68 errno = 0;
69 hostname[k] = '\0';
70 err = gethostname (hostname, size);
71 if (err >= 0 && hostname[k] == '\0')
72 break;
73 else if (err < 0 && errno != ENAMETOOLONG && errno != 0)
75 int saved_errno = errno;
76 free (hostname);
77 errno = saved_errno;
78 return NULL;
80 size *= 2;
81 hostname = xrealloc (hostname, size + 1);
84 return hostname;