Skip to content

Regex to Validate IP Addresses

Jarrod

Asked Jun 12, 2007, 12:42 PM EDT3 answers
Share
LinkedInX
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.

3 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Mike Gold
    0
    It would help to know what the value of the lower_bound you are using to cause the exception.

    best,
    0
  • 0
    It's any given value I give it.

    I've tried:
    0.0.0.0 (Multicast, but should still be a valid IP address, no?)
    10.15.100.
    192.168.1.1 through 192.168.255.255
    255.255.255.255

    Every IP I enter, the same exception pops up.
    0
  • 0
    Regex to Validate IP Addresses
    0