Verify if an IPv4 IP address is valid


/ Published in: Perl
Save to your folder(s)

This code will validate not only the four octets contain between 1 and 3 numbers each, but also that the number they contain is between 0 and 255.

In all, there are 3 different regex's that I tried and all seem to work fine. The three regex's are:

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

The first one is used below. Enjoy!!!


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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.