From: Gunnar Beutner Date: Mon, 26 May 2014 15:32:18 +0000 (+0200) Subject: Make sure that Utility::GetHostName() returns an FQDN. X-Git-Tag: v2.0.0-beta1~12 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=3f2df5b65613009cba5027715d1cfe96d555a6cd;p=icinga2 Make sure that Utility::GetHostName() returns an FQDN. Fixes #6312 --- diff --git a/lib/base/utility.cpp b/lib/base/utility.cpp index 1017346c9..1a741094b 100644 --- a/lib/base/utility.cpp +++ b/lib/base/utility.cpp @@ -22,6 +22,7 @@ #include "base/application.hpp" #include "base/logger_fwd.hpp" #include "base/exception.hpp" +#include "base/socket.hpp" #include #include #include @@ -977,14 +978,42 @@ int Utility::CompareVersion(const String& v1, const String& v2) return 0; } +/** + * Returns the fully-qualified domain name for the host + * we're running on. + * + * @returns The FQDN. + */ String Utility::GetHostName(void) { char name[255]; - if (gethostname(name, sizeof(name)) < 0) - strcpy(name, ""); + if (gethostname(name, sizeof(name)) < 0) { + return "localhost"; + } + + addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; + hints.ai_flags = AI_CANONNAME; + + addrinfo *result; + int rc = getaddrinfo(name, NULL, &hints, &result); + + if (rc < 0) + result = NULL; + + String canonicalName; + + if (result && strcmp(result->ai_canonname, "localhost") != 0) { + canonicalName = result->ai_canonname; + freeaddrinfo(result); + } else { + canonicalName = name; + } - return String(name); + return canonicalName; } int Utility::Random(void)