Monday, December 30, 2013

Expand CIDR Notation in Powershell

This is a repost of code from somewhere else. Running the script when you feed it a CIDR notation IP address will return the last entry requested.

For Example:

EXPANDCIDR "10.0.0.1/24"
10.0.0.255




function ql { $Args }

function ExpandCIDR($CIDR) {
 $bits = ql 0 128 192 224 240 248 252 254
 $net = $cidr.Split("/")
 $sn = $net[0]
 $octets = $sn.Split(".")

 [int]$mask = $net[1]
 $activ = $mask % 8
 $actval = $bits[$activ]
 $fulloctets = [System.Math]::Truncate($mask / 8)

 $ao = [int]$octets[$fulloctets]
 $mn = 256 – $actval
 $x = [System.Math]::Truncate($ao / $mn)
 $num = $x * $mn
 ## calculate active part of broadcast address
 $bd = $num + $mn -1
 switch ($fulloctets)
 {
  1
  {
   $fixed = $octets[0]
   $subnet = $fixed + "." + $num.ToString() + ".0.0"
   $strmask = "255." + $actval.ToString() + ".0.0"
   $broadcast = $fixed + "." + $bd.ToString() + ".255.255" 
   break
  }
  2
  {
   $fixed = $octets[0]+"."+$octets[1]
   $subnet = $fixed + "." + $num.ToString() + ".0"
   $strmask = "255.255." + $actval.ToString() + ".0"
   $broadcast = $fixed + "." + $bd.ToString() + ".255" 
   break
  }
  3
  {
   $fixed = $octets[0]+"."+$octets[1]+"."+$octets[2]
   $subnet = $fixed + "." + $num.ToString()
   $strmask = "255.255.255." + $actval.ToString()
   $broadcast = $fixed + "." + $bd.ToString()
   break
  }
 }

 $snoct = $subnet.Split(".")
 $snoct[3] = ([int]$snoct[3] + 1).ToString()
 $fip = $snoct[0]+"."+$snoct[1]+"."+$snoct[2]+"."+$snoct[3]
 $bdoct = $broadcast.Split(".")
 $bdoct[3] = ([int]$bdoct[3] – 1).ToString()
 $lip = $bdoct[0]+"."+$bdoct[1]+"."+$bdoct[2]+"."+$bdoct[3]
 return $broadcast
}

How I use this is to combine it with this function:


function get-nextaddress {
 param ([string]$address )

 $a = [System.Net.IpAddress]::Parse($address) ## turn the string to IP address
 $z = $a.GetAddressBytes() ## and then to an array of bytes
 if ($z[3] -eq 255) ## last octet full
 {
  $z[3] = 0 ## so reset

  if ($z[2] -eq 255) ## third octet full
  {
   $z[2] = 0 ## so reset   
   $z[1] += 1 ## increment second octet
  }
  else
  {
   $z[2] += 1 ##  increment third octect
  }
 }
 else
 {
  $z[3] += 1 ## increment last octet
 }
 $c = [System.Net.IpAddress]($z) ## recreate IP address
 return $c.ToString()
}

Then loop through all of the IPs in the group.

 $broken=@()
 $lastIP = expandCidr($ip)
 $curradd = $ip.Split("/")[0]
 do {
  $addr = get-nextaddress($curradd)
  Write-Host $addr
  $ipobj = Add-OneIP $addr
  if ($broken -notcontains $ipobj) {$broken += $ipobj}
  $curradd = $addr
 } until ($addr -eq $lastIP)

When done, the variable $Broken contains all of the IPs in the CIDR range.

$IP = "10.0.0.1/24"
<call script above>
10.0.0.1
10.0.0.2
10.0.0.3
...
10.0.0.255

No comments:

Post a Comment