-
-
Save mlhDevelopment/87d3bfca66bb57d73726611a7c153fe8 to your computer and use it in GitHub Desktop.
CIDR to IP range conversion using PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# calculate IP address range from CIDR notation | |
# https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing | |
function cidrToIpRange { | |
param ( | |
[string] $cidrNotation | |
) | |
$addr, $maskLength = $cidrNotation -split '/' | |
[int]$maskLen = 0 | |
if (-not [int32]::TryParse($maskLength, [ref] $maskLen)) { | |
write-warning "No mask, setting to /32" | |
$masklen = 32 | |
} | |
if (0 -gt $maskLen -or $maskLen -gt 32) { | |
throw "CIDR mask length must be between 0 and 32" | |
} | |
$ipAddr = [Net.IPAddress]::Parse($addr) | |
if ($ipAddr -eq $null) { | |
throw "Cannot parse IP address: $addr" | |
} | |
if ($ipAddr.AddressFamily -ne [Net.Sockets.AddressFamily]::InterNetwork) { | |
throw "Can only process CIDR for IPv4" | |
} | |
$shiftCnt = 32 - $maskLen | |
$mask = -bnot ((1 -shl $shiftCnt) - 1) | |
$ipNum = [Net.IPAddress]::NetworkToHostOrder([BitConverter]::ToInt32($ipAddr.GetAddressBytes(), 0)) | |
$ipStart = ($ipNum -band $mask) | |
$ipEnd = ($ipNum -bor (-bnot $mask)) | |
# return | |
return [PSCustomObject]@{ | |
Start = ([BitConverter]::GetBytes([Net.IPAddress]::HostToNetworkOrder($ipStart)) | ForEach-Object { $_ } ) -join '.' | |
End = ([BitConverter]::GetBytes([Net.IPAddress]::HostToNetworkOrder($ipEnd)) | ForEach-Object { $_ } ) -join '.' | |
} | |
} | |
# Test | |
$ips = @('1.2.3.4/24', '9.8.7.6') | |
$ips | % { cidrToIpRange $_ } | sort-object start |
Thanks for this. I've taken a copy of this function to use in a PS module I'm working on at work for managing Exchange server Receive Connectors' RemoteIPRanges. Only change I made was a "#Credits: " line at the top. Thanks very much and nicely done.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yup, you're right. Updated.