Validate IP address with regular expressions and C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • PsychoCoder
    Recognized Expert Contributor
    • Jul 2010
    • 465

    Validate IP address with regular expressions and C#

    I was doing some work for someone and needed to validate an IP address. Now you could use IPAddress.TryPa rse but it allows values like 0.0.0.0, so I used regular expressions and it worked much better.

    Code:
    /// <summary>
    /// method to validate an IP address
    /// using regular expressions. The pattern
    /// being used will validate an ip address
    /// with the range of 1.0.0.0 to 255.255.255.255
    /// </summary>
    /// <param name="addr">Address to validate</param>
    /// <returns></returns>
    public bool IsValidIP(string addr)
    {
        //create our match pattern
        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}$";
        //create our Regular Expression object
        Regex check = new Regex(pattern);
        //boolean variable to hold the status
        bool valid = false;
        //check to make sure an ip address was provided
        if (addr == "")
        {
            //no address provided so return false
            valid = false;
        }
        else
        {
            //address provided so use the IsMatch Method
            //of the Regular Expression object
            valid = check.IsMatch(addr, 0);
        }
        //return the results
        return valid;
    }
    Happy Coding!
  • !NoItAll
    Contributor
    • May 2006
    • 297

    #2
    Ok - I think using TryParse and checking for 0.0.0.0 would be fine too. While the Regex for IPv4 is fairly straight-forward, I think applying this to IPv6 would require an indecipherable regex (e.g. unmaintainable code). Using TryParse creates a much more supportable code base IMHO.

    Comment

    • TomasRiker
      New Member
      • Nov 2012
      • 1

      #3
      I just wrote an article about matching IP addresses with regular expressions. It also has a regex for IPv6 addresses, if you are interested (pretty simple though thanks to hex digits ;)).

      Comment

      Working...