Skip to content

Instantly share code, notes, and snippets.

@jcefoli
Last active July 25, 2023 21:33
Show Gist options
  • Save jcefoli/68ee7420fbf993ea803d08ef5f419129 to your computer and use it in GitHub Desktop.
Save jcefoli/68ee7420fbf993ea803d08ef5f419129 to your computer and use it in GitHub Desktop.
[pwsh] Generate a random IP address in a given CIDR range
function Get-RandomIPAddressInCIDR {
param (
[string]$CIDR
)
# Split the CIDR into network address and subnet mask
$networkAddress, $subnetMaskBits = $CIDR -split '/'
$subnetMaskBits = [int]$subnetMaskBits
if ($subnetMaskBits -eq 32) {
# If the subnet mask is /32, return the network address as the only possible IP
return [IPAddress]::Parse($networkAddress).IPAddressToString
}
# Calculate the number of possible host addresses based on the subnet mask
$possibleHostAddresses = [math]::Pow(2, 32 - $subnetMaskBits) - 2
# Store the original value of $subnetMaskBits
$originalSubnetMaskBits = $subnetMaskBits
do {
# Restore the original value of $subnetMaskBits
$subnetMaskBits = $originalSubnetMaskBits
# Generate a random number within the range of possible host addresses
$randomHostAddress = Get-Random -Minimum 0 -Maximum ($possibleHostAddresses + 1)
# Convert the network address to bytes
$networkBytes = [System.Net.IPAddress]::Parse($networkAddress).GetAddressBytes()
# Convert the random host address to bytes
$randomBytes = [BitConverter]::GetBytes($randomHostAddress)
# Combine the network address bytes with the random host address bytes
$randomIPBytes = for ($i = 0; $i -lt 4; $i++) {
if ($subnetMaskBits -ge 8) {
$subnetMaskBits -= 8
$networkBytes[$i]
}
else {
$mask = [math]::Pow(2, 8 - $subnetMaskBits) - 1
$subnetMaskBits = 0
(($networkBytes[$i] -band (-bnot $mask)) -bor ($randomBytes[$i] -band $mask))
}
}
# Convert the resulting bytes back to an IP address string
$randomIP = [IPAddress]::Parse($randomIPBytes -join '.')
} while ($randomIP.GetAddressBytes()[3] -eq 0 -or $randomIP.GetAddressBytes()[3] -eq 1 -or $randomIP.GetAddressBytes()[3] -eq 254 -or $randomIP.GetAddressBytes()[3] -eq 255) #disallow .0 .1 and .255 as the last octet
return $randomIP.IPAddressToString
}
# Usage example
$cidr = "192.168.1.0/24"
# One IP
Get-RandomIPAddressInCIDR $cidr
# Loop for 20 Random IPs
for ($i = 0; $i -lt 20; $i++) {
$randomIP = Get-RandomIPAddressInCIDR $cidr
$randomIP
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment