TDME2  1.9.200
Network.cpp
Go to the documentation of this file.
2 
3 #include <string.h>
4 
5 #include <openssl/ssl.h>
6 #include <openssl/err.h>
7 
8 #if defined(_WIN32)
9  #include <winsock2.h>
10  #include <ws2tcpip.h>
11 #else
12  #include <netdb.h>
13  #include <arpa/inet.h>
14  #include <netinet/in.h>
15  #include <sys/socket.h>
16 #endif
17 
18 #include <string>
19 
20 #include <tdme/tdme.h>
23 #include <tdme/utilities/Console.h>
24 
26 
27 using std::string;
28 using std::to_string;
29 
33 
34 bool Network::initialize() {
35  // https support
36  SSL_library_init();
37  SSL_load_error_strings();
38  ERR_load_crypto_strings();
39  //
40  #if defined(_WIN32)
41  WSADATA wsaData;
42  auto result = WSAStartup(MAKEWORD(2,2), &wsaData);
43  if (result != 0) {
44  Console::println("WinSock2 initialization failed: " + to_string(result));
45  return false;
46  }
47  #endif
48  return true;
49 }
50 
51 const string Network::getIpByHostname(const string& hostname) {
52  auto hostEnt = gethostbyname(hostname.c_str());
53 
54  if (hostEnt == nullptr) {
55  throw NetworkException("Could not resolve hostname");
56  }
57 
58  switch (hostEnt->h_addrtype) {
59  case AF_INET:
60  if (hostEnt->h_addr_list[0] != nullptr) {
61  struct in_addr addr;
62  addr.s_addr = *(uint32_t*)hostEnt->h_addr_list[0];
63  return string(inet_ntoa(addr));
64  }
65  break;
66  case AF_INET6:
67  if (hostEnt->h_addr_list[0] != nullptr) {
68  char ipv6AddressString[46];
69  return string(inet_ntop(AF_INET6, (in6_addr*)hostEnt->h_addr_list[0], ipv6AddressString, INET6_ADDRSTRLEN) == NULL?"":ipv6AddressString);
70  }
71  break;
72  }
73 
74  throw NetworkException("Could not resolve hostname");
75 }
Base exception class for network exceptions.
Base class of network sockets.
Definition: NetworkSocket.h:17
Network class.
Definition: Network.h:14
static const string getIpByHostname(const string &hostname)
Get IP by hostname.
Definition: Network.cpp:51
Console class.
Definition: Console.h:29