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 ?
How about just System.Net.IPAddress.Parse?
ReplyDeleteA Parse method would throw an exception (a FormatException) whereas the other code snippet in the post would return a boolean false value.
ReplyDeleteI 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 :)