Antares Simulator
Power System Simulator
hostname.hxx
1 /*
2 ** Copyright 2007-2025, RTE (https://www.rte-france.com)
3 ** See AUTHORS.txt
4 ** SPDX-License-Identifier: MPL-2.0
5 ** This file is part of Antares-Simulator,
6 ** Adequacy and Performance assessment for interconnected energy networks.
7 **
8 ** Antares_Simulator is free software: you can redistribute it and/or modify
9 ** it under the terms of the Mozilla Public Licence 2.0 as published by
10 ** the Mozilla Foundation, either version 2 of the License, or
11 ** (at your option) any later version.
12 **
13 ** Antares_Simulator is distributed in the hope that it will be useful,
14 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ** Mozilla Public Licence 2.0 for more details.
17 **
18 ** You should have received a copy of the Mozilla Public Licence 2.0
19 ** along with Antares_Simulator. If not, see <https://opensource.org/license/mpl-2-0/>.
20 */
21 
22 #include <yuni/yuni.h>
23 #ifndef YUNI_OS_MSVC
24 #include <unistd.h>
25 #endif
26 #ifndef YUNI_OS_WINDOWS
27 #include <netdb.h>
28 #else
29 #include <Windns.h>
30 
31 #include <yuni/core/system/windows.hdr.h>
32 #endif
33 
34 namespace // anonymous
35 {
36 template<class AnyStringT>
37 void InternalAppendHostname(AnyStringT& out)
38 {
39 #ifndef YUNI_OS_WINDOWS
40  char hostname[256];
41  if (0 != gethostname(hostname, sizeof(hostname)))
42  {
43  out << "<unknown>";
44  return;
45  }
46  hostname[sizeof(hostname) - 1] = '\0';
47 
48  struct addrinfo hints, *info, *p;
49  int gai_result;
50  memset(&hints, 0, sizeof hints);
51  hints.ai_family = AF_UNSPEC; /*either IPV4 or IPV6*/
52  hints.ai_socktype = SOCK_STREAM;
53  hints.ai_flags = AI_CANONNAME;
54 
55  if ((gai_result = getaddrinfo(hostname, "http", &hints, &info)) != 0)
56  {
57  out << "<unknown>";
58  return;
59  }
60 
61  for (p = info; p != NULL; p = p->ai_next)
62  {
63  const char* const name = p->ai_canonname;
64  if (name and '\0' != *name)
65  {
66  out << name;
67  }
68  }
69 
70  freeaddrinfo(info);
71 
72 #else // windows
73 
74  WSADATA wsaData;
75  const WORD wVersionRequested = MAKEWORD(2, 0);
76 
77  if (WSAStartup(wVersionRequested, &wsaData) == 0)
78  {
79  char name[256];
80  if (gethostname(name, sizeof(name)) == 0)
81  {
82  name[sizeof(name) - 1] = '\0'; // paranoid
83  out << (const char*)name;
84  }
85  else
86  {
87  out << "<unknown>";
88  }
89  WSACleanup();
90  }
91  else
92  {
93  out << "<unknown>";
94  }
95 
96 #endif
97 }
98 
99 } // anonymous namespace