- hostname[size - 1] = '\0';
- err = gethostname (hostname, size);
- if (err == 0 && hostname[size - 1] == '\0')
- break;
- size *= 2;
- hostname = xrealloc (hostname, size);
+ /* Use SIZE_1 here rather than SIZE to work around the bug in
+ SunOS 5.5's gethostname whereby it NUL-terminates HOSTNAME
+ even when the name is as long as the supplied buffer. */
+ size_t size_1;
+
+ hostname = x2realloc (hostname, &size);
+ size_1 = size - 1;
+ hostname[size_1 - 1] = '\0';
+ errno = 0;
+
+ if (gethostname (hostname, size_1) == 0)
+ {
+ if (! hostname[size_1 - 1])
+ break;
+ }
+ else if (errno != 0 && errno != ENAMETOOLONG && errno != EINVAL)
+ {
+ int saved_errno = errno;
+ free (hostname);
+ errno = saved_errno;
+ return NULL;
+ }