1
0

Added IPAddress.Increment/Decrement; Added ParseNetwork, ExpandNetwork

This commit is contained in:
2022-07-24 01:56:44 +02:00
parent 4938becdd7
commit e449176682
5 changed files with 196 additions and 17 deletions

View File

@@ -4,6 +4,7 @@ using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using Microsoft.AspNetCore.HttpOverrides;
namespace AMWD.Common.Utilities
{
@@ -77,6 +78,66 @@ namespace AMWD.Common.Utilities
}
}
/// <summary>
/// Parses a CIDR network definition.
/// </summary>
/// <param name="network">The network in CIDR.</param>
/// <returns>The <see cref="IPNetwork"/> or <c>null</c>.</returns>
public static IPNetwork ParseNetwork(string network)
{
TryParseNetwork(network, out var ipNetwork);
return ipNetwork;
}
/// <summary>
/// Tries to parse a CIDR network definition.
/// </summary>
/// <param name="network">The network in CIDR.</param>
/// <param name="ipNetwork">The parsed <see cref="IPNetwork"/>.</param>
/// <returns><c>true</c> on success, otherwise <c>false</c>.</returns>
public static bool TryParseNetwork(string network, out IPNetwork ipNetwork)
{
try
{
string[] parts = network.Split('/');
if (parts.Length != 2)
throw new ArgumentException($"Invalid network type");
var prefix = IPAddress.Parse(parts.First());
int prefixLength = int.Parse(parts.Last());
ipNetwork = new IPNetwork(prefix, prefixLength);
return true;
}
catch
{
ipNetwork = null;
return false;
}
}
/// <summary>
/// Uses the <see cref="IPNetwork"/> and expands the whole subnet.
/// </summary>
/// <remarks>
/// The network identifier and the broadcast address are included in the response list.
/// </remarks>
/// <param name="network">The <see cref="IPNetwork"/> to expand.</param>
/// <returns>A list with all valid <see cref="IPAddress"/>es.</returns>
public static List<IPAddress> ExpandNetwork(this IPNetwork network)
{
var list = new List<IPAddress>();
var ipAddress = network.Prefix;
while (network.Contains(ipAddress))
{
list.Add(ipAddress);
ipAddress = ipAddress.Increment();
}
return list;
}
private static IPAddress ResolveIpAddress(string address, AddressFamily addressFamily)
{
if (IPAddress.TryParse(address, out var ipAddress))