For example, How do I validate that the IP range 192.168.2.0/24 is in IPV4 or IPV6 CIDR format?
Need help modifying:
public static bool IsValidIP(string address)
{
IPAddress ip;
if (!IPAddress.TryParse(address, out ip)) return false;
switch (ip.AddressFamily)
{
case AddressFamily.InterNetwork:
if (address.Length > 6 && address.Contains("."))
{
string[] s = address.Split('.');
if (s.Length == 4 && s[0].Length > 0 && s[1].Length > 0 && s[2].Length > 0 && s[3].Length > 0)
return true;
}
break;
case AddressFamily.InterNetworkV6:
if (address.Contains(":") && address.Length > 15)
return true;
break;
}
return false;
}
CIDR always ends with a "/xx", so just knock that off if it exists and parse the stuff before using the IPAddress
class.
using System.Net;
var input = "192.168.2.0/24";
// or
var input = "2345:0425:2CA1:0000:0000:0567:5673:23b5/64";
var segments = input.Split('/');
var isValidIpAddress = IPAddress.TryParse(segments[0], out var parsedAddress);
Console.WriteLine(parsedAddress.AddressFamily);
var isCIDR = segments.Length is 2; // you should also validate segments[1]
// is an allowed value as well based on
// the IP version.