0

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?

5
  • 1
    Please explain "wrong result". What is the expected result? How do you test? Commented Nov 22, 2023 at 13:18
  • 1
    Please show at least one CIDR address, the results this code produced, and the desired results. MRE Commented Nov 22, 2023 at 14:27
  • 1
    nuget.org/packages/IPNetwork2 makes this really easy ;) Commented Nov 22, 2023 at 14:36
  • I'm afraid you wont get out of this without going through binary notation as based on your prefix it is uncertain that lower boundary is the prefix or below. E.g. 192.168.1.0/23 goes from 192.168.0.0 to 192.168.1.255 (including network and broadcast. Commented Nov 22, 2023 at 14:40
  • 1
    This one works: gist.github.com/davidjenni/7eb707e60316cdd97549b37ca95fbe93 Commented Nov 22, 2023 at 16:07

1 Answer 1

1

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.