How to validate textbox for IPV4 and IPV6 IPAddresses.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • fastestindian
    New Member
    • Aug 2009
    • 74

    How to validate textbox for IPV4 and IPV6 IPAddresses.

    Hi,

    I am working on the validations of the entered ip addresses but not able to validate using existing methods.
    such as IPAddress.TryPa rse(addrString, out address);

    so pls give me some suggessions on this as i have wasted lot of time on it.

    Thanks in advance.
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    You could do it through Regular Expressions (RegEx)

    Code:
    /// 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;
    }

    Comment

    • Plater
      Recognized Expert Expert
      • Apr 2007
      • 7872

      #3
      Depending on your need, you would want to include 0.0.0.0 as well

      Comment

      Working...