Skip to content

Instantly share code, notes, and snippets.

@agowa
Last active August 19, 2020 16:37
Show Gist options
  • Save agowa/bd2d90d180c12ddf8c29e9b075cff3b4 to your computer and use it in GitHub Desktop.
Save agowa/bd2d90d180c12ddf8c29e9b075cff3b4 to your computer and use it in GitHub Desktop.
# This script uses this library: https://github.com/lduchosal/ipnetwork
# It needs to be imported using e.g. `Add-Type -AssemblyName ./System.Net.IPNetwork.dll`
# Not to be confused with IPNetwork from Microsoft.AspNetCore.HttpOverrides.dll
function Get-CIDRFromAddressByPrefixList {
[OutputType([System.Net.IPNetwork])]
param(
[Parameter(Mandatory)][System.Net.IPAddress]$address,
[Parameter(Mandatory)][System.Net.IPNetwork[]]$prefixes
)
$address6 = $address.MapToIPv6()
if ($address6.IsIPv4MappedToIPv6) { $address = $address6.MapToIPv4() }
$netmask128 = [System.Net.IPAddress]"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
foreach ($prefix in $prefixes) {
$network6 = $prefix.Network.MapToIPv6()
$netmask6 = [System.Net.IPAddress]::new(([BigInt]$prefix.Netmask.MapToIPv6().GetAddressBytes() + [BigInt]([System.Net.IPAddress]"ffff:ffff:ffff:ffff:ffff::").GetAddressBytes()).ToByteArray())
$prefix6 = [System.Net.IPNetwork]::Parse($network, $netmask)
if ($prefix6.Overlap( [System.Net.IPNetwork]::Parse($address6, $netmask128) )) {
$CIDRString = '{0}/{1}' -f $address6, $netmask6
return $CIDRString
}
}
}
function Get-UnmappedAddress {
[OutputType([String])]
param(
[PArameter(Mandatory)][String]$CIDR
)
[System.Net.IPAddress]$IPAddress, [int]$CIDRSuffix = $CIDR -split '/'
if ($IPAddress.IsIPv4MappedToIPv6) {
$CIDR = '{0}/{1}' -f $IPAddress.MapToIPv4().IPAddressToString, $CIDRSuffix - 96
} else {
$CIDR = '{0}/{1}' -f $IPAddress.IPAddressToString, $CIDRSuffix
}
return $CIDR
}
function Test-IsIPv4 {
[OutputType([Boolean])]
param(
[Parameter(Mandatory)][System.Net.IPAddress]$IPAddress
)
if ($IPAddress.IsIPv4MappedToIPv6 -or ($IPAddress.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork)) {
return $true
} else {
return $false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment