mirror of https://github.com/fairyglade/ly.git
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'.
This commit is contained in:
parent
4dee666dcf
commit
4e69002432
23
src/util.c
23
src/util.c
|
|
@ -6,7 +6,6 @@
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
|
|
||||||
// hostname
|
|
||||||
#include <limits.h>
|
#include <limits.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <sys/types.h>
|
#include <sys/types.h>
|
||||||
|
|
@ -24,23 +23,27 @@ void hostname(char** out)
|
||||||
struct addrinfo hints;
|
struct addrinfo hints;
|
||||||
struct addrinfo* info;
|
struct addrinfo* info;
|
||||||
char* hostname;
|
char* hostname;
|
||||||
char* dot;
|
|
||||||
int host_name_max;
|
|
||||||
int result;
|
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)");
|
maxlen = _POSIX_HOST_NAME_MAX;
|
||||||
exit(1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((hostname = malloc(host_name_max+1)) == NULL)
|
if ((hostname = malloc(maxlen + 1)) == NULL)
|
||||||
{
|
{
|
||||||
perror("malloc");
|
perror("malloc");
|
||||||
exit(1);
|
exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
gethostname(hostname, sizeof(hostname));
|
if (gethostname(hostname, maxlen) < 0)
|
||||||
|
{
|
||||||
|
perror("gethostname");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
hostname[maxlen] = '\0';
|
||||||
|
|
||||||
memset(&hints, 0, sizeof hints);
|
memset(&hints, 0, sizeof hints);
|
||||||
hints.ai_family = AF_UNSPEC;
|
hints.ai_family = AF_UNSPEC;
|
||||||
hints.ai_socktype = SOCK_STREAM;
|
hints.ai_socktype = SOCK_STREAM;
|
||||||
|
|
@ -49,8 +52,9 @@ void hostname(char** out)
|
||||||
|
|
||||||
if ((result == 0) && (info != NULL))
|
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);
|
*out = strndup(info->ai_canonname, dot - info->ai_canonname);
|
||||||
|
freeaddrinfo(info);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
|
@ -58,7 +62,6 @@ void hostname(char** out)
|
||||||
}
|
}
|
||||||
|
|
||||||
hostname_backup = *out;
|
hostname_backup = *out;
|
||||||
freeaddrinfo(info);
|
|
||||||
free(hostname);
|
free(hostname);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue