Skip to content

Instantly share code, notes, and snippets.

@Martyr2
Created June 1, 2017 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Martyr2/da763e170925dcdaa91f26186a0b9b0c to your computer and use it in GitHub Desktop.
Save Martyr2/da763e170925dcdaa91f26186a0b9b0c to your computer and use it in GitHub Desktop.
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