Skip to content

Instantly share code, notes, and snippets.

@Badgerati
Last active March 30, 2018 11:24
Show Gist options
  • Save Badgerati/c8b1bee06d81b58177dd7b9e36de79b5 to your computer and use it in GitHub Desktop.
Save Badgerati/c8b1bee06d81b58177dd7b9e36de79b5 to your computer and use it in GitHub Desktop.
Given a subnet mask like 10.0.1.0/24, will return the lowest and highest addresses across the range
<#
.DESCRIPTION
Given a subnet mask, will return the lowest and highest addresses within the range of the mask.
For example, given 10.1.4.0/24, will return @{"lowest"="10.1.4.0", "highest"="10.1.4.255"}
.EXAMPLE
Get-SubnetRange -SubnetMask '10.1.4.0/24'
#>
function Get-SubnetRange
{
param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$SubnetMask
)
# split for ip and number of 1 bits
$split = $SubnetMask -split '/'
$ip = $split[0]
$ip_parts = $ip -isplit '\.'
$bits = [int]$split[1]
# generate the netmask
$network = @("", "", "", "")
$count = 0
foreach ($i in 0..3)
{
foreach ($b in 1..8)
{
$count++
if ($count -le $bits)
{
$network[$i] += "1"
}
else
{
$network[$i] += "0"
}
}
}
# covert netmask to bytes
0..3 | ForEach-Object {
$network[$_] = [Convert]::ToByte($network[$_], 2)
}
# calculate the bottom range
$bottom = @(0..3 | ForEach-Object { [byte]([byte]$network[$_] -band [byte]$ip_parts[$_]) })
# calculate the range
$range = @(0..3 | ForEach-Object { 256 + (-bnot [byte]$network[$_]) })
# calculate the top range
$top = @(0..3 | ForEach-Object { [byte]([byte]$ip_parts[$_] + [byte]$range[$_]) })
return @{
'lowest' = ($bottom -join '.');
'highest' = ($top -join '.');
'range' = ($range -join '.');
'netmask' = ($network -join '.');
'ip' = ($ip_parts -join '.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment