Monday, August 27, 2007

Validating IP addresses

The common way to validate IP addresses is with Regular expressions. This method helps determine whether a string is a valid IP address. It uses the Parse method of the system.net.ipaddress NET class.

The function returns a boolean value with respect to the tests result.

 

function Validate-IPAddress{
    param([string]$ip=$(throw "Missing IP address argument"))
    trap{$false; continue;}
    [bool][system.net.ipaddress]::Parse($ip);
}

 

 

# Some usage examples

>> Validate-IPAddress "192.168.1.27"
True

Validate-IPAddress "192.168.1.274"
False

 

# common if/else testing
>> $ip="192.168.1.27";
>> if(Validate-IPAddress $ip){
>> "$ip is Valid";
>> } else {
>> write-warning "$ip is NOT Valid";
>> }

192.168.1.27 is Valid

 

# test for false value
# -not logical operator can be replaced with "!"

>> $ip="192.168.1.274";
>> if(-not (Validate-IPAddress $ip)){
>> write-warning "$ip is NOT Valid";
>> }

WARNING: 192.168.1.274 is NOT Valid

3 comments:

Anonymous said...

Validate-IPAddress "192"

True

Anonymous said...

Validate-IPAddress "192"

True

Anonymous said...

Validate-IPAddress "192"

True