diff --git a/c/unix/socket.c b/c/unix/socket.c index 6ea2271..69ddb44 100644 --- a/c/unix/socket.c +++ b/c/unix/socket.c @@ -381,11 +381,38 @@ s48_close_socket_half(s48_value channel, s48_value input_p) static s48_value s48_get_host_name(void) { - char mbuff[MAXHOSTNAMELEN]; + char *mbuff = NULL; + size_t mbuff_len = 0; + int status = 0; + s48_value name; - if (gethostname(mbuff, sizeof(mbuff)) < 0) + do { + char *tmp; + + mbuff_len += 256; /* Initial guess */ + tmp = (char *) realloc(mbuff, mbuff_len); + + if (tmp == NULL) { + free(mbuff); + s48_raise_os_error(ENOMEM); + } + else + mbuff = tmp; + } while (((status = gethostname(mbuff, mbuff_len)) == 0 + && !memchr(mbuff, '\0', mbuff_len)) +#ifdef ENAMETOOLONG + || errno == ENAMETOOLONG +#endif + ); + + if (status != 0 && errno != 0) { + /* gethostname failed, abort. */ + free(mbuff); s48_raise_os_error(errno); - - return s48_enter_string(mbuff); + } + + name = s48_enter_string(mbuff); + free(mbuff); + return name; }