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