Skip to content

Instantly share code, notes, and snippets.

@Badgerati
Last active March 30, 2018 17:56
Show Gist options
  • Save Badgerati/0206f6a66dcd603149d19307995ebf9e to your computer and use it in GitHub Desktop.
Save Badgerati/0206f6a66dcd603149d19307995ebf9e to your computer and use it in GitHub Desktop.
Given the low and high addresses of a subnet range, will return the subnet mask of the range
<#
.DESCRIPTION
Given the low and high addresses of a subnet range, will return the subnet mask of the range.
For example, given 10.0.0.64 and 10.0.0.95, will return "10.0.0.64/27"
.EXAMPLE
Get-SubnetMask -Low '10.0.0.64' -High '10.0.0.95'
#>
function Get-SubnetMask
{
param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$Low,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$High
)
# split low and high
$low_parts = $Low -split '\.'
$high_parts = $High -split '\.'
# subtract and bitwise not to get network
$network = @(0..3 | ForEach-Object { 256 + (-bnot ([byte]$high_parts[$_] - [byte]$low_parts[$_])) })
# convert the network to binary
$binary = ((($network | ForEach-Object { [Convert]::ToString($_, 2) }) -join '') -split '0')[0] -join ''
$binary = $binary + (New-Object String -ArgumentList "0", (32 - $binary.Length))
# re-calc the network and low address
$network = @(0..3 | ForEach-Object { [Convert]::ToByte(($binary[($_ * 8)..(($_ * 8) + 7)] -join ''), 2) })
$Low = @(0..3 | ForEach-Object { [byte]([byte]$network[$_] -band [byte]$low_parts[$_]) }) -join '.'
# count the 1 bits of the network
$bits = ($binary.ToCharArray() | ForEach-Object { Invoke-Expression $_ } | Measure-Object -Sum).Sum
# return the mask
return "$($Low)/$($bits)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment