From 4e690024320f0e276c42c795e8830a454a15d53a Mon Sep 17 00:00:00 2001 From: Aaron LI Date: Sat, 6 Oct 2018 01:34:04 +0800 Subject: [PATCH] util: Fix gethostname() and freeaddrinfo() calls I was passing the wrong size to the 'gethostname()' call because the 'hostname' is now dynamically allocated and cannot use 'sizeof' to get its size. This mistake causes that the obtained hostname is empty. The 'freeaddrinfo()' was placed at the wrong place. Fix it. Fallback to '_POSIX_HOST_NAME_MAX' if 'sysconf()' fails. Always null-terminate the 'hostname'. --- src/util.c | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/util.c b/src/util.c index b3f8eef..7e75f62 100644 --- a/src/util.c +++ b/src/util.c @@ -6,7 +6,6 @@ #include #include -// hostname #include #include #include @@ -24,23 +23,27 @@ void hostname(char** out) struct addrinfo hints; struct addrinfo* info; char* hostname; - char* dot; - int host_name_max; int result; - if ((host_name_max = sysconf(_SC_HOST_NAME_MAX)) == -1) + int maxlen = sysconf(_SC_HOST_NAME_MAX); + if (maxlen < 0) { - perror("sysconf(_SC_HOST_NAME_MAX)"); - exit(1); + maxlen = _POSIX_HOST_NAME_MAX; } - if ((hostname = malloc(host_name_max+1)) == NULL) + if ((hostname = malloc(maxlen + 1)) == NULL) { perror("malloc"); exit(1); } - gethostname(hostname, sizeof(hostname)); + if (gethostname(hostname, maxlen) < 0) + { + perror("gethostname"); + exit(1); + } + hostname[maxlen] = '\0'; + memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; @@ -49,8 +52,9 @@ void hostname(char** out) if ((result == 0) && (info != NULL)) { - dot = strchr(info->ai_canonname, '.'); + char* dot = strchr(info->ai_canonname, '.'); *out = strndup(info->ai_canonname, dot - info->ai_canonname); + freeaddrinfo(info); } else { @@ -58,7 +62,6 @@ void hostname(char** out) } hostname_backup = *out; - freeaddrinfo(info); free(hostname); }