# Posted By

numberwhun on 06/05/07

# Statistics

Viewed 1972 times
Favorited by 0 user(s)

# Verify if an IPv4 IP address is valid

/ Published in: Perl  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
`#!/usr/bin/perl use strict;use warnings;  print("What is the IP Address you would like to validate: ");my \$ipaddr = <STDIN>;chomp(\$ipaddr);  if( \$ipaddr =~ m/^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\$/ ){    print("IP Address \$ipaddr  -->  VALID FORMAT! \n");     if(\$1 <= 255 && \$2 <= 255 && \$3 <= 255 && \$4 <= 255)    {        print("IP address:  \$1.\$2.\$3.\$4  -->  All octets within range\n");    }    else    {        print("One of the octets is out of range.  All octets must contain a number between 0 and 255 \n");    }}else{    print("IP Address \$ipaddr  -->  NOT IN VALID FORMAT! \n");}` Subscribe to comments