network_connection.hpp
1 #pragma once
2 
3 #include "global.hpp"
4 
5 #include "string.hpp"
6 
7 namespace Cvb
8 {
9 CVB_BEGIN_INLINE_NS
10 
12 
15 {
16  typedef String IPAddress;
18  typedef std::uint16_t Port;
19 
20  IPAddressUInt ipAddressUInt_{0u};
21  IPAddress ipAddress_{CVB_LIT("0.0.0.0")};
22  Port port_{0u};
23 
24  NetworkConnection() noexcept {}
25 
26  NetworkConnection(const IPAddress &ip, const Port &port) : ipAddress_(ip), port_(port)
27  {
28  ipAddressUInt_ = ToIPAddressUInt(ipAddress_);
29  }
30 
31  NetworkConnection(const IPAddressUInt &ipUInt, const Port &port) : ipAddressUInt_(ipUInt), port_(port)
32  {
33  ipAddress_ = ToIPAddress(ipAddressUInt_);
34  }
35 
42  static IPAddress ToIPAddress(const IPAddressUInt &ipAddressInt)
43  {
44  unsigned char bytes[4];
45  bytes[3] = ipAddressInt & 0xFF;
46  bytes[2] = (ipAddressInt >> 8) & 0xFF;
47  bytes[1] = (ipAddressInt >> 16) & 0xFF;
48  bytes[0] = (ipAddressInt >> 24) & 0xFF;
49 
50  std::string str = std::to_string((int)bytes[0]);
51  str += "." + std::to_string(static_cast<int>(bytes[1]));
52  str += "." + std::to_string(static_cast<int>(bytes[2]));
53  str += "." + std::to_string(static_cast<int>(bytes[3]));
54 
55  return IPAddress(str.begin(), str.end());
56  }
57 
65  {
66  std::string _ip (Internal::CastToAscii(ip));
67  char *runner = const_cast<char *>(_ip.c_str());
68  unsigned long factor = 1;
69  IPAddressUInt temp = 0;
70  unsigned int reset = 0;
71 
72  while (*runner)
73  runner++;
74 
75  while ((_ip.c_str() - runner--))
76  {
77  if (*runner == '.')
78  {
79  factor <<= 8;
80  reset = 0;
81  runner--;
82  }
83  temp += (factor * static_cast<unsigned long>(*(runner) - '0') * (reset == 1 ? 10 : (reset == 2 ? 100 : 1)));
84  reset++;
85  }
86  return temp;
87  }
88 };
89 
90 CVB_END_INLINE_NS
91 }
static IPAddressUInt ToIPAddressUInt(const IPAddress &ip)
Creates an uint ip . from the given IPAddress
Definition: network_connection.hpp:64
Basic network connection operations.
Definition: network_connection.hpp:14
static IPAddress ToIPAddress(const IPAddressUInt &ipAddressInt)
Creates an IPAddress from the given uint ip .
Definition: network_connection.hpp:42
STL class.
Root namespace for the Image Manager interface.
Definition: version.hpp:11