Tuesday, June 05, 2007

IPv4 Address validation

Well, in my quest to learn Perl and practice putting together regex's, I took on the task yesterday of putting together a script which validates if an IP address is valid or not. Now, when you say "is valid", what exactly does that mean?

Well, there are two criteria that IP addresses need to really meet:

1) They need to have 4 octets, each octet containing from 1 to 3 digits.
2) Each octet's digits must make up a number between 0 and 255.

With that in mind, I went directly after the first of the two, validating the format of the IP address entered. The regex that I initially came up with is listed in #1 and the other two regex's came from the "Mastering Regular Expressions" book:

#1 m/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/
#2 m/\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?/
#3 m/\d(\d\d?)?\.\d(\d\d?)?\.\d(\d\d?)?\.\d(\d\d?)?/

What is so great about Perl is TIMTOWTDI, which affords us being able to have 3 different regex's that come to exactly the same solution.

You may be asking yourself, what do I do with the regex(s) above? Well, you can take them and use them in your code to validate an entered IP address, or put it into a loop to test an entire file full of IP's to test their validity.

Here is an example of how to incorporate the above regex(s) into some code. Please know that this is only how I do it and my differ considerably from how you implement it:


  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. print("What is the IP Address you would like to validate: ");
  5. my $ipaddr = ;
  6. chomp($ipaddr);
  7. if( $ipaddr =~ m/^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)/ )
  8. {
  9. print("IP Address $ipaddr --> VALID FORMAT! \n");
  10. if($1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255)
  11. {
  12. print("IP address: $1.$2.$3.$4 --> All octets within range\n");
  13. }
  14. else
  15. {
  16. print("One of the octets is out of range. All octets must contain a number between 0 and 255 \n");
  17. }
  18. }
  19. else
  20. {
  21. print("IP Address $ipaddr --> NOT IN VALID FORMAT! \n");
  22. }

Well, there you go, IP address validation. No, this script obviously does not take into account IPs that are reseverd such as the 192.168 or 10.246 addresses, but you can test for whatever you need to given the grouping in the regex that provides the $1, $2, $3 and $4 variables.

Happy Perl Coding!!!

2 comments:

Anonymous said...

Thanks. Just put this to good use on an internal script I use for DNS resolution

Numberwhun said...

That's awesome. I am so glad it was able to help you. :)

 
Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 License.