Validate IP Address string (alternative)


posted by Thomas Lee
11-29-2008

Downloads: 487
File size: 505 B
Views: 3,884

Embed
Validate IP Address string (alternative)
  1. # Get-IPAddress2.ps1 
  2. # Parses an address, returns a System.NET.IPAddress if OK 
  3. # Uses tryparse (and therefore works with PSH v1) 
  4. # Thomas Lee - tfl@psp.co.uk 
  5.  
  6. $strings = "10.1.1.100", "10.1", "fooey" 
  7.  
  8. foreach( $string in $strings){ 
  9. "Testing: `"{0}`"" -f $string 
  10. $address = [System.Net.IPAddress]::tryparse($string,[ref] $ip1
  11. if ($address ){ 
  12.   "`"{0}`" `tis a valid IP address" -f [System.Net.IPAddress]::parse($string
  13. }   
  14. else
  15.   "`"{0}`" `tis NOT a valid IP address" -f $string 
  16.  
This script demonstrates an alternative way to validate an string as being an IP address using [system.net.ipaddress]::try(). This method returns a true/false value to say if the string is a valid IP address, and it returns a [ref] value of the IPAddress object. Compare this with: http://powershell.com/cs/media/13/default.aspx

Comments

Aleksandar wrote re: Validate IP Address string (alternative)
on 11-30-2008 3:06 PM

Just because input string can be parsed, it doesn't mean it is a valid IP Address. TryParse does a great job of coercing a value into a valid IP address, but we have to compare the input string to the result of the TryParse.

function IsValidIP {

param($string)

# [ref] cannot be applied to a variable that does not exist.

$IPAddress = $null

([System.Net.IPAddress]::tryparse($string,[ref]$IPAddress) -and $string -eq $IPaddress.tostring())

}

tbaker012 wrote re: Validate IP Address string (alternative)
on 02-23-2011 2:28 PM

It seems that 10.1 comes up as a valid IP address with the code above.

Testing: "10.1.1.100"

"10.1.1.100" is a valid IP address

Testing: "10.1"

"10.1" is a valid IP address

Testing: "fooey"

"fooey" is NOT a valid IP address

I added the following line so that only an address with 4 octets is accepted as valid.

$HasFourOctets = (($string.split(".") | Measure-Object).count -eq 4)

The code as modified now looks like this.

$strings = "10.1.1.100", "10.1", "fooey"

foreach( $string in $strings){  

"Testing: `"{0}`"" -f $string

$HasFourOctets = (($string.split(".") | Measure-Object).count -eq 4)

$address = [System.Net.IPAddress]::tryparse($string,[ref] $ip1)  

if ($address -and $HasFourOctets){  

 "`"{0}`" `tis a valid IP address" -f [System.Net.IPAddress]::parse($string)  

}    

else {  

 "`"{0}`" `tis NOT a valid IP address" -f $string  

}

The output now looks like.

Testing: "10.1.1.100"

"10.1.1.100" is a valid IP address

Testing: "10.1"

"10.1" is NOT a valid IP address

Testing: "fooey"

"fooey" is NOT a valid IP address

Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.