Jarrod

Jarrod

  • NA
  • 3
  • 0

Regex to Validate IP Addresses

Jun 12 2007 4:42 PM
Hi all. New member to the community here.

I'm working on a ping sweep program for my office here, and I'm having some trouble with my exception handling. When I run the program, the regex seems to pick up when the upper bound of the IP range is not a valid address, but when I test the lower bound, it gives me the "Input string is not correct format" unhandled exception. I don't understand why it would spit an error for one and not the other. Here's the code snippet:

try
            {
                string pattern = @"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b";
                Regex regex = new Regex(pattern);
                Match match = regex.Match(lower_bound);
                Match match2 = regex.Match(upper_bound);
                while (!match.Success)
                {
                    throw new FormatException();
                }
               
                while (!match2.Success)
                {
                    throw new FormatException();
                }

            }
            catch (FormatException)
            {
                MessageBox.Show("Please enter a valid IP address (x.x.x.x).");
                return;
            }


Thanks in advance.

Answers (3)