Thursday, August 4, 2011

How to Validate an IPv4 Address in Perl Using Regular Expressions

Validating IP Addresses in Perl

When checking if a string is a valid IPv4 address (where each of the four octets must be between 0 and 255), you have two primary approaches in Perl: combining a simple regex with numeric condition checks, or using one complex regex that handles the numeric limits natively.

Method 1: Simple Regex with Numeric Range Checks
This method extracts the four numbers using capture groups (\d+) and then uses a standard if statement to ensure each number falls within the valid 0-255 range. This is often much easier to read and maintain.

Perl
$ip =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/;

if ($1 >= 0 && $1 <= 255 && 
    $2 >= 0 && $2 <= 255 && 
    $3 >= 0 && $3 <= 255 && 
    $4 >= 0 && $4 <= 255) 
{
    # Valid IP Address
}

Method 2: Pure Regular Expression (No If-Statement)
This method uses a more complex regular expression to ensure the numbers match the 0-255 range directly within the pattern match itself. It checks for numbers starting with 2[0-5][0-5] (200-255) or 1?[0-9]?[0-9] (0-199).
Perl
# Validates the IP range directly in the regex match
$ip =~ /\b((2[0-5][0-5]\.)|(1?[0-9]?[0-9]\.)){3}((2[0-5][0-5])|(1?[0-9]?[0-9]))\b/;

No comments: