Added IPAddress.Increment/Decrement; Added ParseNetwork, ExpandNetwork
This commit is contained in:
@@ -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))
|
||||
|
||||
Reference in New Issue
Block a user