Generate IP range from CIDR notation issue in powershell

245 Views Asked by At

I have the following powershell function, and I want to return the IP range from a CIDR.

Here is the code:

function ConvertFrom-CidrNotation {
    param(
        [Parameter(Mandatory=$true)]
        [string]$cidr
    )

    $parts = $cidr -split "/"
    $ip = $parts[0]
    $prefix = $parts[1]

    $subnet = [math]::pow(2, (32 - $prefix))
    $startIP = ([System.Net.IPAddress]::Parse($ip).GetAddressBytes() | ForEach-Object{ $_ -bor 0 }) -join "."
    
    # Correct the end IP calculation
    $ipBytes = [System.Net.IPAddress]::Parse($ip).GetAddressBytes()
    $subnetBytes = [BitConverter]::GetBytes([int]$subnet)
    $endIPBytes = for ($i = 0; $i -lt 4; $i++) { $ipBytes[$i] -bor $subnetBytes[$i] }
    $endIP = $endIPBytes -join "."

    return "$startIP - $endIP"
}

Please, can you tell me why I get wrong results?

1

There are 1 best solutions below

0
On

Use following to get start address

$ip = '192.3.6.8' -split '\.'

$startIP = 0
for($i = 3; $i -ge 0; $i--)
{
   $startIP += ([int]::Parse($ip[3-$i])) -shl (8 * $i)
}

Write-Host $startIP.ToString("x4")