| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.Globalization; |
| | | 6 | | using System.Net.NetworkInformation; |
| | | 7 | | using System.Net.Sockets; |
| | | 8 | | using System.Numerics; |
| | | 9 | | using System.Runtime.CompilerServices; |
| | | 10 | | using System.Runtime.InteropServices; |
| | | 11 | | |
| | | 12 | | namespace System.Net |
| | | 13 | | { |
| | | 14 | | internal static class IPAddressParser |
| | | 15 | | { |
| | | 16 | | internal const int MaxIPv4StringLength = 15; // 4 numbers separated by 3 periods, with up to 3 digits per number |
| | | 17 | | internal const int MaxIPv6StringLength = 65; |
| | | 18 | | |
| | | 19 | | public static bool IsValid<TChar>(ReadOnlySpan<TChar> ipSpan) |
| | | 20 | | where TChar : unmanaged, IBinaryInteger<TChar> |
| | 4192 | 21 | | { |
| | 4192 | 22 | | if (ipSpan.Contains(TChar.CreateTruncating(':'))) |
| | 2389 | 23 | | { |
| | 2389 | 24 | | return IPv6AddressHelper.IsValidStrict(ipSpan); |
| | | 25 | | } |
| | | 26 | | else |
| | 1803 | 27 | | { |
| | 1803 | 28 | | long address = IPv4AddressHelper.ParseNonCanonical(ipSpan, out int end, notImplicitFile: true); |
| | 1803 | 29 | | return address != IPv4AddressHelper.Invalid && end == ipSpan.Length; |
| | | 30 | | } |
| | 4192 | 31 | | } |
| | | 32 | | |
| | | 33 | | internal static unsafe IPAddress? Parse<TChar>(ReadOnlySpan<TChar> ipSpan, bool tryParse) |
| | | 34 | | where TChar : unmanaged, IBinaryInteger<TChar> |
| | 3531 | 35 | | { |
| | 3531 | 36 | | Debug.Assert(typeof(TChar) == typeof(byte) || typeof(TChar) == typeof(char)); |
| | | 37 | | |
| | 3531 | 38 | | if (ipSpan.Contains(TChar.CreateTruncating(':'))) |
| | 1851 | 39 | | { |
| | | 40 | | // The address is parsed as IPv6 if and only if it contains a colon. This is valid because |
| | | 41 | | // we don't support/parse a port specification at the end of an IPv4 address. |
| | 1851 | 42 | | Span<ushort> numbers = stackalloc ushort[IPAddressParserStatics.IPv6AddressShorts]; |
| | 1851 | 43 | | numbers.Clear(); |
| | 1851 | 44 | | if (TryParseIPv6(ipSpan, numbers, IPAddressParserStatics.IPv6AddressShorts, out uint scope)) |
| | 1076 | 45 | | { |
| | 1076 | 46 | | return new IPAddress(numbers, scope); |
| | | 47 | | } |
| | 775 | 48 | | } |
| | 1680 | 49 | | else if (TryParseIpv4(ipSpan, out long address)) |
| | 246 | 50 | | { |
| | 246 | 51 | | return new IPAddress(address); |
| | | 52 | | } |
| | | 53 | | |
| | 2209 | 54 | | if (tryParse) |
| | 2209 | 55 | | { |
| | 2209 | 56 | | return null; |
| | | 57 | | } |
| | | 58 | | |
| | 0 | 59 | | throw new FormatException(SR.dns_bad_ip_address, new SocketException(SocketError.InvalidArgument)); |
| | 3531 | 60 | | } |
| | | 61 | | |
| | | 62 | | private static bool TryParseIpv4<TChar>(ReadOnlySpan<TChar> ipSpan, out long address) |
| | | 63 | | where TChar : unmanaged, IBinaryInteger<TChar> |
| | 1680 | 64 | | { |
| | 1680 | 65 | | long tmpAddr = IPv4AddressHelper.ParseNonCanonical(ipSpan, out int end, notImplicitFile: true); |
| | | 66 | | |
| | 1680 | 67 | | if (tmpAddr != IPv4AddressHelper.Invalid && end == ipSpan.Length) |
| | 246 | 68 | | { |
| | | 69 | | // IPv4AddressHelper.ParseNonCanonical returns the bytes in host order. |
| | | 70 | | // Convert to network order and return success. |
| | 246 | 71 | | address = (uint)IPAddress.HostToNetworkOrder(unchecked((int)tmpAddr)); |
| | 246 | 72 | | return true; |
| | | 73 | | } |
| | | 74 | | |
| | | 75 | | // Failed to parse the address. |
| | 1434 | 76 | | address = 0; |
| | 1434 | 77 | | return false; |
| | 1680 | 78 | | } |
| | | 79 | | |
| | | 80 | | private static bool TryParseIPv6<TChar>(ReadOnlySpan<TChar> ipSpan, Span<ushort> numbers, int numbersLength, out |
| | | 81 | | where TChar : unmanaged, IBinaryInteger<TChar> |
| | 1851 | 82 | | { |
| | 1851 | 83 | | Debug.Assert(typeof(TChar) == typeof(char) || typeof(TChar) == typeof(byte)); |
| | 1851 | 84 | | Debug.Assert(numbersLength >= IPAddressParserStatics.IPv6AddressShorts); |
| | | 85 | | |
| | 1851 | 86 | | if (!IPv6AddressHelper.IsValidStrict(ipSpan)) |
| | 775 | 87 | | { |
| | 775 | 88 | | scope = 0; |
| | 775 | 89 | | return false; |
| | | 90 | | } |
| | | 91 | | |
| | 1076 | 92 | | IPv6AddressHelper.Parse(ipSpan, numbers, out ReadOnlySpan<TChar> scopeIdSpan); |
| | | 93 | | |
| | 1076 | 94 | | if (scopeIdSpan.Length > 1) |
| | 302 | 95 | | { |
| | | 96 | | bool parsedNumericScope; |
| | 302 | 97 | | scopeIdSpan = scopeIdSpan.Slice(1); |
| | | 98 | | |
| | | 99 | | // scopeId is a numeric value |
| | 302 | 100 | | if (typeof(TChar) == typeof(byte)) |
| | 151 | 101 | | { |
| | 151 | 102 | | ReadOnlySpan<byte> castScopeIdSpan = MemoryMarshal.Cast<TChar, byte>(scopeIdSpan); |
| | | 103 | | |
| | 151 | 104 | | parsedNumericScope = uint.TryParse(castScopeIdSpan, NumberStyles.None, CultureInfo.InvariantCulture, |
| | 151 | 105 | | } |
| | | 106 | | else |
| | 151 | 107 | | { |
| | 151 | 108 | | ReadOnlySpan<char> castScopeIdSpan = MemoryMarshal.Cast<TChar, char>(scopeIdSpan); |
| | | 109 | | |
| | 151 | 110 | | parsedNumericScope = uint.TryParse(castScopeIdSpan, NumberStyles.None, CultureInfo.InvariantCulture, |
| | 151 | 111 | | } |
| | | 112 | | |
| | 302 | 113 | | if (parsedNumericScope) |
| | 34 | 114 | | { |
| | 34 | 115 | | return true; |
| | | 116 | | } |
| | | 117 | | else |
| | 268 | 118 | | { |
| | 268 | 119 | | uint interfaceIndex = InterfaceInfoPal.InterfaceNameToIndex(scopeIdSpan); |
| | | 120 | | |
| | 268 | 121 | | if (interfaceIndex > 0) |
| | 2 | 122 | | { |
| | 2 | 123 | | scope = interfaceIndex; |
| | 2 | 124 | | return true; // scopeId is a known interface name |
| | | 125 | | } |
| | 266 | 126 | | } |
| | | 127 | | |
| | | 128 | | // scopeId is an unknown interface name |
| | 266 | 129 | | } |
| | | 130 | | |
| | | 131 | | // scopeId is not presented |
| | 1040 | 132 | | scope = 0; |
| | 1040 | 133 | | return true; |
| | 1851 | 134 | | } |
| | | 135 | | |
| | | 136 | | internal static int FormatIPv4Address<TChar>(uint address, Span<TChar> addressString) |
| | | 137 | | where TChar : unmanaged, IBinaryInteger<TChar> |
| | 208 | 138 | | { |
| | 208 | 139 | | address = (uint)IPAddress.NetworkToHostOrder(unchecked((int)address)); |
| | | 140 | | |
| | 208 | 141 | | int pos = FormatByte(address >> 24, addressString); |
| | 208 | 142 | | addressString[pos++] = TChar.CreateTruncating('.'); |
| | 208 | 143 | | pos += FormatByte(address >> 16, addressString.Slice(pos)); |
| | 208 | 144 | | addressString[pos++] = TChar.CreateTruncating('.'); |
| | 208 | 145 | | pos += FormatByte(address >> 8, addressString.Slice(pos)); |
| | 208 | 146 | | addressString[pos++] = TChar.CreateTruncating('.'); |
| | 208 | 147 | | pos += FormatByte(address, addressString.Slice(pos)); |
| | | 148 | | |
| | 208 | 149 | | return pos; |
| | | 150 | | |
| | | 151 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 152 | | static int FormatByte(uint number, Span<TChar> addressString) |
| | 832 | 153 | | { |
| | 832 | 154 | | number &= 0xFF; |
| | | 155 | | |
| | 832 | 156 | | if (number >= 10) |
| | 198 | 157 | | { |
| | | 158 | | uint hundreds, tens; |
| | 198 | 159 | | if (number >= 100) |
| | 60 | 160 | | { |
| | 60 | 161 | | (uint hundredsAndTens, number) = Math.DivRem(number, 10); |
| | 60 | 162 | | (hundreds, tens) = Math.DivRem(hundredsAndTens, 10); |
| | | 163 | | |
| | 60 | 164 | | addressString[2] = TChar.CreateTruncating('0' + number); |
| | 60 | 165 | | addressString[1] = TChar.CreateTruncating('0' + tens); |
| | 60 | 166 | | addressString[0] = TChar.CreateTruncating('0' + hundreds); |
| | 60 | 167 | | return 3; |
| | | 168 | | } |
| | | 169 | | |
| | 138 | 170 | | (tens, number) = Math.DivRem(number, 10); |
| | 138 | 171 | | addressString[1] = TChar.CreateTruncating('0' + number); |
| | 138 | 172 | | addressString[0] = TChar.CreateTruncating('0' + tens); |
| | 138 | 173 | | return 2; |
| | | 174 | | } |
| | | 175 | | |
| | 634 | 176 | | addressString[0] = TChar.CreateTruncating('0' + number); |
| | 634 | 177 | | return 1; |
| | 832 | 178 | | } |
| | 208 | 179 | | } |
| | | 180 | | |
| | | 181 | | internal static int FormatIPv6Address<TChar>(ushort[] address, uint scopeId, Span<TChar> destination) |
| | | 182 | | where TChar : unmanaged, IBinaryInteger<TChar> |
| | 538 | 183 | | { |
| | 538 | 184 | | Debug.Assert(typeof(TChar) == typeof(byte) || typeof(TChar) == typeof(char)); |
| | 538 | 185 | | int pos = 0; |
| | | 186 | | |
| | 538 | 187 | | if (IPv6AddressHelper.ShouldHaveIpv4Embedded(address)) |
| | 85 | 188 | | { |
| | | 189 | | // We need to treat the last 2 ushorts as a 4-byte IPv4 address, |
| | | 190 | | // so output the first 6 ushorts normally, followed by the IPv4 address. |
| | 85 | 191 | | AppendSections(address.AsSpan(0, 6), destination, ref pos); |
| | 85 | 192 | | if (destination[pos - 1] != TChar.CreateTruncating(':')) |
| | 0 | 193 | | { |
| | 0 | 194 | | destination[pos++] = TChar.CreateTruncating(':'); |
| | 0 | 195 | | } |
| | | 196 | | |
| | 85 | 197 | | pos += FormatIPv4Address(ExtractIPv4Address(address), destination.Slice(pos)); |
| | 85 | 198 | | } |
| | | 199 | | else |
| | 453 | 200 | | { |
| | | 201 | | // No IPv4 address. Output all 8 sections as part of the IPv6 address |
| | | 202 | | // with normal formatting rules. |
| | 453 | 203 | | AppendSections(address.AsSpan(0, 8), destination, ref pos); |
| | 453 | 204 | | } |
| | | 205 | | |
| | | 206 | | // If there's a scope ID, append it. |
| | 538 | 207 | | if (scopeId != 0) |
| | 16 | 208 | | { |
| | 16 | 209 | | destination[pos++] = TChar.CreateTruncating('%'); |
| | | 210 | | |
| | | 211 | | int bytesWritten; |
| | 16 | 212 | | bool formatted = typeof(TChar) == typeof(byte) ? |
| | 16 | 213 | | scopeId.TryFormat(MemoryMarshal.Cast<TChar, byte>(destination).Slice(pos), out bytesWritten) : |
| | 16 | 214 | | scopeId.TryFormat(MemoryMarshal.Cast<TChar, char>(destination).Slice(pos), out bytesWritten); |
| | | 215 | | |
| | 16 | 216 | | Debug.Assert(formatted); |
| | 16 | 217 | | pos += bytesWritten; |
| | 16 | 218 | | } |
| | | 219 | | |
| | 538 | 220 | | return pos; |
| | | 221 | | |
| | | 222 | | // Appends each of the numbers in address in indexed range [fromInclusive, toExclusive), |
| | | 223 | | // while also replacing the longest sequence of 0s found in that range with "::", as long |
| | | 224 | | // as the sequence is more than one 0. |
| | | 225 | | static void AppendSections(ReadOnlySpan<ushort> address, Span<TChar> destination, ref int offset) |
| | 538 | 226 | | { |
| | | 227 | | // Find the longest sequence of zeros to be combined into a "::" |
| | 538 | 228 | | (int zeroStart, int zeroEnd) = IPv6AddressHelper.FindCompressionRange(address); |
| | 538 | 229 | | bool needsColon = false; |
| | | 230 | | |
| | | 231 | | // Handle a zero sequence if there is one |
| | 538 | 232 | | if (zeroStart >= 0) |
| | 440 | 233 | | { |
| | | 234 | | // Output all of the numbers before the zero sequence |
| | 1726 | 235 | | for (int i = 0; i < zeroStart; i++) |
| | 423 | 236 | | { |
| | 423 | 237 | | if (needsColon) |
| | 207 | 238 | | { |
| | 207 | 239 | | destination[offset++] = TChar.CreateTruncating(':'); |
| | 207 | 240 | | } |
| | 423 | 241 | | needsColon = true; |
| | 423 | 242 | | AppendHex(address[i], destination, ref offset); |
| | 423 | 243 | | } |
| | | 244 | | |
| | | 245 | | // Output the zero sequence if there is one |
| | 440 | 246 | | destination[offset++] = TChar.CreateTruncating(':'); |
| | 440 | 247 | | destination[offset++] = TChar.CreateTruncating(':'); |
| | 440 | 248 | | needsColon = false; |
| | 440 | 249 | | } |
| | | 250 | | |
| | | 251 | | // Output everything after the zero sequence |
| | 3386 | 252 | | for (int i = zeroEnd; i < address.Length; i++) |
| | 1155 | 253 | | { |
| | 1155 | 254 | | if (needsColon) |
| | 873 | 255 | | { |
| | 873 | 256 | | destination[offset++] = TChar.CreateTruncating(':'); |
| | 873 | 257 | | } |
| | 1155 | 258 | | needsColon = true; |
| | 1155 | 259 | | AppendHex(address[i], destination, ref offset); |
| | 1155 | 260 | | } |
| | 538 | 261 | | } |
| | | 262 | | |
| | | 263 | | // Appends a number as hexadecimal (without the leading "0x") |
| | | 264 | | static void AppendHex(ushort value, Span<TChar> destination, ref int offset) |
| | 1578 | 265 | | { |
| | 1578 | 266 | | if ((value & 0xFFF0) != 0) |
| | 854 | 267 | | { |
| | 854 | 268 | | if ((value & 0xFF00) != 0) |
| | 531 | 269 | | { |
| | 531 | 270 | | if ((value & 0xF000) != 0) |
| | 236 | 271 | | { |
| | 236 | 272 | | destination[offset++] = TChar.CreateTruncating(HexConverter.ToCharLower(value >> 12)); |
| | 236 | 273 | | } |
| | | 274 | | |
| | 531 | 275 | | destination[offset++] = TChar.CreateTruncating(HexConverter.ToCharLower(value >> 8)); |
| | 531 | 276 | | } |
| | | 277 | | |
| | 854 | 278 | | destination[offset++] = TChar.CreateTruncating(HexConverter.ToCharLower(value >> 4)); |
| | 854 | 279 | | } |
| | | 280 | | |
| | 1578 | 281 | | destination[offset++] = TChar.CreateTruncating(HexConverter.ToCharLower(value)); |
| | 1578 | 282 | | } |
| | 538 | 283 | | } |
| | | 284 | | |
| | | 285 | | /// <summary>Extracts the IPv4 address from the end of the IPv6 address byte array.</summary> |
| | | 286 | | private static uint ExtractIPv4Address(ushort[] address) |
| | 85 | 287 | | { |
| | 85 | 288 | | uint ipv4address = (uint)address[6] << 16 | address[7]; |
| | 85 | 289 | | return (uint)IPAddress.HostToNetworkOrder(unchecked((int)ipv4address)); |
| | 85 | 290 | | } |
| | | 291 | | } |
| | | 292 | | } |
| | | 293 | | |