You ever have the need to validate whether the user entered a valid IP address? Regular expressions come in really handy here. However, if you do some searching online for a good regex to accomplish this, you'll undoubtedly come across some regular expressions that are pretty lousy or only half-baked.
When validating an IP address, we only want to accept values between 0.0.0.0 and 255.255.255.255. I wrote the following function which seems to do the trick nicely:
[UPDATE: 09/28/2006]
As mentioned by a few of the readers, my initial regular expression was shortsighted and I overlooked a subset of numbers. I've updated my solution to use a suggestion by AleXX below, which correctly validates an ip address from 1.0.0.0 to 255.255.255.255.
Thanks for the observations, guys, and the corrections. I'll be more thorough in the future.
public bool IsValidIPAddress(string ipAddr) {
string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";
Regex reg = new Regex(pattern, RegexOptions.Singleline | RegexOptions.ExplicitCapture);
return reg.IsMatch(ipAddr);
}