Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 119,059 C# Programmers for FREE! Ask your question and get quick answers from experts. There are 1,445 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!




Validate IP address with Regular Expression

This is a snippet I use to validate IP address using regular expressions. I use this when working in .Net 1.1 as the TryParse method isnt available until 2.0

Submitted By: PsychoCoder
Actions:
Rating:
Views: 10,956

Language: C#

Last Modified: October 31, 2007
Instructions: Pass the method an ip address. Add

using System.Net

To your code file

Snippet


  1. /// <summary>
  2. /// method to validate an IP address
  3. /// using regular expressions. The pattern
  4. /// being used will validate an ip address
  5. /// with the range of 1.0.0.0 to 255.255.255.255
  6. /// </summary>
  7. /// <param name="addr">Address to validate</param>
  8. /// <returns></returns>
  9. public bool IsValidIP(string addr)
  10. {
  11.     //create our match pattern
  12.     string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.
  13.     ([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";
  14.     //create our Regular Expression object
  15.     Regex check = new Regex(pattern);
  16.     //boolean variable to hold the status
  17.     bool valid = false;
  18.     //check to make sure an ip address was provided
  19.     if (addr == "")
  20.     {
  21.         //no address provided so return false
  22.         valid = false;
  23.     }
  24.     else
  25.     {
  26.         //address provided so use the IsMatch Method
  27.         //of the Regular Expression object
  28.         valid = check.IsMatch(addr, 0);
  29.     }
  30.     //return the results
  31.     return valid;
  32. }

Copy & Paste


Comments


killnine 2008-02-18 13:04:51

Nice job on the match pattern. Its kinda hard to make good regular expressions from my limited experience. Thanks for the sample code. For more regular expressions, check out: http://regexlib.com/


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month