| 100 | */ |
| 101 | |
| 102 | String IpAddress::ToString() const |
| 103 | { |
| 104 | StringStream stream; |
| 105 | |
| 106 | if (m_isValid) |
| 107 | { |
| 108 | NazaraAssert(m_protocol <= NetProtocol_Max, "Protocol has value out of enum"); |
| 109 | switch (m_protocol) |
| 110 | { |
| 111 | case NetProtocol_Any: |
| 112 | case NetProtocol_Unknown: |
| 113 | break; |
| 114 | |
| 115 | case NetProtocol_IPv4: |
| 116 | for (unsigned int i = 0; i < 4; ++i) |
| 117 | { |
| 118 | stream << int(m_ipv4[i]); |
| 119 | if (i != 3) |
| 120 | stream << '.'; |
| 121 | } |
| 122 | break; |
| 123 | |
| 124 | case NetProtocol_IPv6: |
| 125 | // Canonical representation of an IPv6 |
| 126 | // https://tools.ietf.org/html/rfc5952 |
| 127 | |
| 128 | // Find the longest zero sequence |
| 129 | unsigned int f0 = std::numeric_limits<unsigned int>::max(); |
| 130 | unsigned int l0 = std::numeric_limits<unsigned int>::max(); |
| 131 | |
| 132 | for (unsigned int i = 0; i < 8; ++i) |
| 133 | { |
| 134 | if (m_ipv6[i] == 0) |
| 135 | { |
| 136 | unsigned int j; |
| 137 | for (j = i + 1; j < 8; ++j) |
| 138 | { |
| 139 | if (m_ipv6[j] != 0) |
| 140 | break; |
| 141 | } |
| 142 | |
| 143 | if (j - i > std::max<unsigned int>(l0 - f0, 1)) |
| 144 | { |
| 145 | f0 = i; |
| 146 | l0 = j; |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | // We need brackets around our IPv6 address if we have a port |
| 152 | if (m_port != 0) |
| 153 | stream << '['; |
| 154 | |
| 155 | for (unsigned int i = 0; i < 8; ++i) |
| 156 | { |
| 157 | if (i == f0) |
| 158 | { |
| 159 | stream << "::"; |
no test coverage detected