Skip to content

Instantly share code, notes, and snippets.

@smoonlee
Created July 23, 2024 08:09
Show Gist options
  • Save smoonlee/ed494fa994f8840122c435ffb205618d to your computer and use it in GitHub Desktop.
Save smoonlee/ed494fa994f8840122c435ffb205618d to your computer and use it in GitHub Desktop.
function Get-UsableAddressSpace {
param (
[Parameter(Mandatory = $true)]
[string]$CIDR
)
# Function to convert IP address to integer
function ConvertTo-Int {
param ($ip)
$i = 0
$ip.Split('.') | ForEach-Object { [int]$_ } | ForEach-Object { $_ -shl 8 * (3 - $i++) } | Measure-Object -Sum | Select-Object -ExpandProperty Sum
}
# Function to convert integer to IP address
function ConvertTo-IP {
param ($int)
$bytes = 3..0 | ForEach-Object { ($int -shr 8 * $_) -band 255 }
return ($bytes -join '.')
}
# Extract base IP and subnet mask
$baseIP, $prefix = $CIDR -split '/'
$prefix = [int]$prefix
# Convert base IP to integer
$baseInt = ConvertTo-Int -ip $baseIP
# Calculate subnet mask and network size
$subnetMask = ([math]::Pow(2, 32) - [math]::Pow(2, 32 - $prefix))
$networkSize = [math]::Pow(2, 32 - $prefix)
# Calculate network and broadcast addresses
$networkInt = $baseInt -band $subnetMask
$broadcastInt = $networkInt + $networkSize - 1
# Calculate first and last usable IP addresses
$firstUsableInt = $networkInt + 1
$lastUsableInt = $broadcastInt - 1
# Convert back to IP addresses
$firstUsableIP = ConvertTo-IP -int $firstUsableInt
$lastUsableIP = ConvertTo-IP -int $lastUsableInt
# Output results
[PSCustomObject]@{
CIDR = $CIDR
NetworkAddress = ConvertTo-IP -int $networkInt
BroadcastAddress = ConvertTo-IP -int $broadcastInt
FirstUsableIP = $firstUsableIP
LastUsableIP = $lastUsableIP
UsableHostCount = $lastUsableInt - $firstUsableInt + 1
}
}
# Example usage
Get-UsableAddressSpace -CIDR "192.168.0.0/21"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment