diff options
Diffstat (limited to 'MediaBrowser.Common/Net/NetworkUtils.cs')
| -rw-r--r-- | MediaBrowser.Common/Net/NetworkUtils.cs | 43 |
1 files changed, 37 insertions, 6 deletions
diff --git a/MediaBrowser.Common/Net/NetworkUtils.cs b/MediaBrowser.Common/Net/NetworkUtils.cs index e482089f0..24ed47a81 100644 --- a/MediaBrowser.Common/Net/NetworkUtils.cs +++ b/MediaBrowser.Common/Net/NetworkUtils.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; @@ -102,7 +103,7 @@ public static partial class NetworkUtils Span<byte> bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? NetworkConstants.IPv4MaskBytes : NetworkConstants.IPv6MaskBytes]; if (!mask.TryWriteBytes(bytes, out var bytesWritten)) { - Console.WriteLine("Unable to write address bytes, only ${bytesWritten} bytes written."); + Console.WriteLine("Unable to write address bytes, only {0} bytes written.", bytesWritten.ToString(CultureInfo.InvariantCulture)); } var zeroed = false; @@ -197,14 +198,25 @@ public static partial class NetworkUtils /// <returns><c>True</c> if parsing was successful.</returns> public static bool TryParseToSubnet(ReadOnlySpan<char> value, [NotNullWhen(true)] out IPNetwork? result, bool negated = false) { + // If multiple IP addresses are in a comma-separated string, the individual addresses may contain leading and/or trailing whitespace value = value.Trim(); + + bool isAddressNegated = false; + if (value.StartsWith('!')) + { + isAddressNegated = true; + value = value[1..]; // Remove leading '!' character + } + + if (isAddressNegated != negated) + { + result = null; + return false; + } + if (value.Contains('/')) { - if (negated && value.StartsWith("!") && IPNetwork.TryParse(value[1..], out result)) - { - return true; - } - else if (!negated && IPNetwork.TryParse(value, out result)) + if (IPNetwork.TryParse(value, out result)) { return true; } @@ -325,4 +337,23 @@ public static partial class NetworkUtils return new IPAddress(BitConverter.GetBytes(broadCastIPAddress)); } + + /// <summary> + /// Check if a subnet contains an address. This method also handles IPv4 mapped to IPv6 addresses. + /// </summary> + /// <param name="network">The <see cref="IPNetwork"/>.</param> + /// <param name="address">The <see cref="IPAddress"/>.</param> + /// <returns>Whether the supplied IP is in the supplied network.</returns> + public static bool SubnetContainsAddress(IPNetwork network, IPAddress address) + { + ArgumentNullException.ThrowIfNull(address); + ArgumentNullException.ThrowIfNull(network); + + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + return network.Contains(address); + } } |
