An Unrivaled Windows Hosting Experience
1-888-313-9421  | webteam@orcsweb.com

Fun with PowerShell: Testing whether an IPv4 address has a valid structure.

More fun with PowerShell today! Today's script is a function, testIP, that accepts a string input and verifies whether it is a valid IPv4 address. Someday I will write one for IPv6, but I need to figure out how exactly those 128-bits worth of rules work. *shudders*


  1. function testIP {   
  2.     param ([string]$tempIP)   
  3.   
  4.     # used for validation   
  5.     $ValidIp = $True  
  6.   
  7.     # test 1: check for proper octet length.   
  8.     [array]$crushIt = $tempIP.split('.')   
  9.     if ($crushIt.length -ne 4) {   
  10.         "The IP $tempIP is invalid. Invalid character or not enough octets."  
  11.         $ValidIp = $False  
  12.         break   
  13.     }   
  14.   
  15.   
  16.     # test 2: check for invalid characters   
  17.     if ($ValidIP) {   
  18.         # this string array stored the chars 1-9 for later testing.   
  19.         $num = "0","1","2","3","4","5","6","7","8","9"  
  20.         foreach ($oct in $crushIT) {   
  21.             $mashIt = $oct.ToCharArray()   
  22.             foreach ($m in $mashIt) {   
  23.                 if ($num -notcontains $m -and $ValidIp) {   
  24.                     "The IP $tempIP contains invalid characters."  
  25.                     $ValidIp = $False  
  26.                     break   
  27.                 }   
  28.             }   
  29.                
  30.             # test for out of range octets   
  31.             if ($ValidIP) {   
  32.                 [int32]$n = $oct  
  33.                 if ($n -lt 0 -or $n -gt 254) {   
  34.                     "$oct in $tempIP is out of range."  
  35.                     $ValidIp = $False  
  36.                     break   
  37.                 }   
  38.             }   
  39.         }   
  40.     }   
  41.     # output results...change to 'return $ValidIp' to pass result to another function.   
  42.     write-output $ValidIp  
  43. }  

Let’s break it down, shall we? And, as usual, there may be better or perhaps built-in ways to do this. I’m not an expert programmer so doing stuff like this is a good learning experience for me, and may be helpful to someone down the line.

First let me define what $ValidIp is and what it does. This a Boolean variable used to validate and store the results of the tests. If at any point during the function a test fails, all of the following tests will simply not run. With a couple of foreach exceptions. In the end, $ValidIp, is used to return or output the result of the tests.

Test 1 is very simple. I use the split method of System.String to divide the string into parts, with a period (.) as the separator. The values are stored in an array named $crushIt. The if-statement then checks the length of the array (i.e. how many strings are in there). If that number is not 4, the number of octets in an IPv4 address, then the test fails and $ValidIp is changed to $False.

Test 2 is a wee bit more complex, as it checks to make sure each character entered is a number. First it runs a check to see if test 1 failed. If it hasn’t, then the script moves along. An array is built with the character values of the numbers 0-9, followed by a foreach loop which goes through every octect. I did it this way to make test 3 go smoothly.

$mashIt is created by converting the octet to a character array, another nifty method in System.String, and then sent through yet another foreach loop. Inside this loop each character is compared to the array storing the string values of the numbers 0-9. If any character doesn’t fit the mold the fashion show ends in tears and sorrow, $ValidIp is set to false and test 3 is summarily ignored (where the tears and sorrow come into play).

Test 3 is the easiest rule of them all. After checking whether $ValidIp is true or false, it converts the string value of the octet to an integer (if true that is). Remember, we already made sure only numbers are involved in test 2 so there will be no conversion errors here. I looked for an hour trying to figure out the convert command, only to discover you just have to save the string to an integer variable, by using [int] or [int32] before the variable name, and PowerShell does the conversion automagically. Well, technically .NET does it, but let’s not get too picky.

Once the conversion is done a very simple if-statement is run to see whether the value of the integer is less than zero or greater than 254. If that statement is false then $ValidIp is set to false. And now we’re done.

I know there are a lot of other tests that could be run, especially if subnet mask was added in the picture, but that’s not the purpose of this function. This is a very simple function to make sure a letter or extra number was not fat fingered into an IP range. The script I am building this for is adds IPs to a server, this function just makes sure the script doesn’t try to add IPs 192.168.1.2 through 192.168.1.2000 to the server and cause all sorts of fun and exciting errors.

0 comment(s) so far