Validate a string for being a Valid IP Address using .NET/C# code

Googled a bit for this but could not find anything. Then turned to my living .NET google - Aniket Palkar. Once again - Kneel down to the deep .NET knowledge pool.

Problem: Validate a string to check if it contains a valid IP Address. I mean 455.12.56.999 should be kicked out.

Here's the quick and simple way :
if(UriHostNameType.IPv4 == Uri.CheckHostName(sStringThatShouldContainIP) ||
UriHostNameType.IPv6 == Uri.CheckHostName(sStringThatShouldContainIP))
This will return if the specified string is IPv4 or v6 or just a DNS style name. Thanks to the guy who wrote this .NET class.. I'm 're-using' or mooching this one.

Here's my was-to-be-unleashed-uber Plan B:
Use this regex from Expresso with some boilerplate regex matching .NET Code.

A point to human searches against online searches ?


  1. How about just System.Net.IPAddress.Parse?

  2. A Parse method would throw an exception (a FormatException) whereas the other code snippet in the post would return a boolean false value.
    I would need a try-catch block to go along with Parse.

    Just my personal phobia of using exception-based code for a common scenario like the user typing an address incorrectly.

    Both should work. Thanks for posting.. it made me look up Parse again :)