validate IP

how can check if the given text was a valid IP format




Answer this question

validate IP

  • cderose

    Try regular expressions:

    string ip = "192.168.100.100";

    Regex regex = new Regex("[0-2][0-9][0-9]\\.[0-2][0-9][0-9]\\.[0-2][0-9][0-9]\\.[0-2][0-9][0-9]");

    Console.WriteLine(regex.Match(ip).Success);

    The expression itself might not be sufficient (depends on your input string), it requires each numer to have 3 digits. A better can be found here: http://www.regular-expressions.info/examples.html


  • raq

    Translated:

    public function IsAddressValid(byval addrString as string) as Boolean

    Dim address as IPAddress = nothing
    return IPAddress.TryParse(addrString, address)

    end sub



  • levitymn

     agrt wrote:

    You could also use System.Net.IPAddress.TryParse. Here's an example:

    public bool IsAddressValid(string addrString)
    {
    IPAddress address;
    return IPAddress.TryParse(addrString, out address);
    }

    Creating the IPAddress may seem excessive if you're just doing validation, but it may perform better than using a regular expression. Your results may vary.

    hi

    i have the same problem and have not much expirience with VB 2005. can u please explain this for VB

    thanks


  • doener

    hi ,

    i would prefer the IPAddress.TryParse instead of creating a whole regex expression.

    i feel Regex is more costly.Also it uses tryparse so no exceptions causing performance issues.

    thanks

    vinothkumar



  • dki

    You could also use System.Net.IPAddress.TryParse. Here's an example:

    public bool IsAddressValid(string addrString)
    {
    IPAddress address;
    return IPAddress.TryParse(addrString, out address);
    }

    Creating the IPAddress may seem excessive if you're just doing validation, but it may perform better than using a regular expression. Your results may vary.



  • humbroll

    yes that is correct

    Regex is expensive but should be used when carrying out large operations as its more worthwhile.

    I wonder if it can parse IPv6....



  • thomaskremmel

    it works.^^
  • validate IP