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.
(?2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?2[0-4]\d|25[0-5]|[01]?\d\d?)

A point to human searches against online searches ?

2 comments:

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

    ReplyDelete
  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 :)

    ReplyDelete