Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Become a C# Expert!

Join 149,027 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,884 people online right now. 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: 14,680

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.




Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month