From 64ffd5fd9526762e27d97e13c59cc6552c97e7bc Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 09:45:57 +0200 Subject: Move subnet parser to NetworkExtensions --- MediaBrowser.Common/Net/NetworkExtensions.cs | 58 +++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 55ec322f4..4cba1c99f 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -1,5 +1,6 @@ +using Microsoft.AspNetCore.HttpOverrides; using System; -using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Sockets; @@ -136,6 +137,61 @@ namespace MediaBrowser.Common.Net return str; } + /// + /// Try parsing an array of strings into subnets, respecting exclusions. + /// + /// Input string to be parsed. + /// Collection of . + /// Boolean signaling if negated or not negated values should be parsed. + /// True if parsing was successful. + public static bool TryParseSubnets(string[] values, out Collection result, bool negated = false) + { + result = new Collection(); + + if (values == null || values.Length == 0) + { + return false; + } + + for (int a = 0; a < values.Length; a++) + { + string[] v = values[a].Trim().Split("/"); + + var address = IPAddress.None; + if (negated && v[0].StartsWith('!')) + { + _ = IPAddress.TryParse(v[0][1..], out address); + } + else if (!negated) + { + _ = IPAddress.TryParse(v[0][0..], out address); + } + + if (address != IPAddress.None && address != null) + { + if (int.TryParse(v[1], out var netmask)) + { + result.Add(new IPNetwork(address, netmask)); + } + else if (address.AddressFamily == AddressFamily.InterNetwork) + { + result.Add(new IPNetwork(address, 32)); + } + else if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + result.Add(new IPNetwork(address, 128)); + } + } + } + + if (result.Count > 0) + { + return true; + } + + return false; + } + /// /// Attempts to parse a host string. /// -- cgit v1.2.3