Thursday, September 20, 2012

Validate IP Address Using Perl

Hi, most of you People would have learned about Perl from Books and PDFs. So here we directly dive into the world of programming. Lets start with a very easy task.

How to Validate an IP address?

I am sure that most of you people would have got this as your assignement or as a question in your Interview.
We can give a simple regular expression as solution for this.

my $ip;   #ip address
$ip = <STDIN>;
chomp($ip);
if ($ip =~ m/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)
{
      print "Valid IP\n";
}
else
{
      print "Invalid IP\n";
}


Try this code for various possible value. It will work for most of the cases.
Give this as input - 1.2.3.4.5
Is this valid IP? - No!!!
But the script will an output "Valid IP".

Now lets modify the code.


my $ip;   #ip address
$ip = <STDIN>;
chomp($ip);
if ($ip =~ m/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)
{
      print "Valid IP\n";
}
else
{
      print "Invalid IP\n";
}

Now give input as 1.2.3.4.5
The output must be Invalid IP

Try giving IP as 320.1.256.700
What is the output?
Valid IP right!!! But this is not a valid IP. We need to put one more check. Because each node in IP will be from 0 to 255.

my $ip;   #ip address
$ip = <STDIN>;
chomp($ip);
if ($ip =~ m/^((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}))$/)
{
      if ((($1 > -1) && ($1 < 256)) && (($2 > -1) && ($2 < 256)) && ( ($3 > -1) && ($3 < 256)) && (($4 > -1) && ($4 < 256)))
      {
           print "Valid IP\n";
      }
      else
      {
           print "Invalid IP\n";
      }
}
else
{
      print "Invalid IP\n";
}

Now every cases will be working fine. Try yourself now. :)