C# validate IP address string


Easy regular expression based IP address validation functions to validate IPV4 address string and by parsing IPV6 address we can validate IPV6 address.

Regular expressions to validate IPV4 addresses

private static readonly Regex validIpV4AddressRegex = new Regex(@"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", RegexOptions.IgnoreCase);

Using above two regular expressions you can validate IP addresses strings in C#.

Example

/// <summary>
/// Validates an IPv4 address.
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
public static bool IsIpV4AddressValid(string address)
{
    if (!string.IsNullOrWhiteSpace(address))
    {
        return validIpV4AddressRegex.IsMatch(address.Trim());
    }

    return false;
}

/// <summary>
/// Validates an IPv6 address.
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
public static bool IsIpV6AddressValid(string address)
{
    if (!string.IsNullOrWhiteSpace(address))
    {
        IPAddress ip;
        if (IPAddress.TryParse(address, out ip))
        {
            return ip.AddressFamily == AddressFamily.InterNetworkV6;
        }
    }
    return false;
}