Skip to content

Instantly share code, notes, and snippets.

@Martyr2 Martyr2/ValidIP.cs
Created Jun 1, 2017

Embed
What would you like to do?
A few utility functions for checking if an IP address is a IPv4 or IPv6 address.
/// <summary>
/// Checks if the supplied address string is an IPv4 version IP address.
/// </summary>
/// <param name="address">IP address to check for being IPv4 (minus any port)</param>
/// <returns>True if the address conforms to IPv4. False otherwise.</returns>
public static bool IsIPv4(string address)
{
string octetRegex = "([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])";
System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(String.Format(@"^{0}\.{0}\.{0}\.{0}$", octetRegex));
return regEx.IsMatch(address);
}
/// <summary>
/// Checks if the supplied address string is an IPv6 version IP address.
/// </summary>
/// <param name="address">IP address to check for being IPv6 (minus any port)</param>
/// <returns>True if the address conforms to IPv6. False otherwise.</returns>
public static bool IsIPv6(string address)
{
UriHostNameType typeName = Uri.CheckHostName(address);
return (typeName == UriHostNameType.IPv6);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.