Compare-IPinSubnet.ps1


<#PSScriptInfo
 
.VERSION 1.0.0
 
.GUID 1d67ba06-2a20-4e05-8b63-8f8c30075c77
 
.AUTHOR saw-friendship
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS IPSubnet calc cidr
 
.LICENSEURI
 
.PROJECTURI https://sawfriendship.wordpress.com/
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
#>


<#
 
.DESCRIPTION
 check that the address is in the IP Subnet
 
.LINK
https://sawfriendship.wordpress.com/2017/06/20/subnet-contains-ip/
 
.EXAMPLE
Compare-IPSubnet -CIDR 8.8.0.0/16 -IP 8.8.8.8
True
 
.EXAMPLE
Get-NetRoute -AddressFamily IPv4 | ? {Compare-IPSubnet -CIDR $_.DestinationPrefix -IP 8.8.8.8}
 
ifIndex DestinationPrefix NextHop RouteMetric ifMetric PolicyStore
------- ----------------- ------- ----------- -------- -----------
8 8.8.0.0/16 192.168.0.201 1 25 ActiveStore
8 0.0.0.0/0 192.168.0.1 0 25 ActiveStore
 
PS>
 
.EXAMPLE
Get-NetRoute -AddressFamily IPv4 | ? {Compare-IPSubnet -CIDR $_.DestinationPrefix -IP 8.8.8.8} | Select-Object -Property DestinationPrefix,NextHop,@{n='PrefixLength'; e = {$_.DestinationPrefix -replace '^[\d\.]+(\\|\/)',''}} | Sort-Object -Property PrefixLength -Descending | Select-Object -First 1
 
DestinationPrefix NextHop PrefixLength
----------------- ------- ------------
8.8.0.0/16 192.168.0.201 16
  
#>
 

param (
    [string]$CIDR,
    [string]$IP
)

[int]$PrefixLength = $CIDR -replace '^[\d\.]+(\\|\/)',''
[string]$Subnet = $CIDR -replace '(\\|\/)\d+$',''
$SplitSubnetBin = $Subnet -split '\.' -match '\d' | % {[convert]::ToString($_,2).PadLeft(8,'0')}
$SubnetBin = $SplitSubnetBin -join ''
$SplitIPBin = $IP -split '\.' -match '\d' | % {[convert]::ToString($_,2).PadLeft(8,'0')}
$IPBin = $SplitIPBin -join ''
[bool]$Result = $true
for ($i = 0; $i -lt $PrefixLength; $i += 1) {
    [bool]$diff = [convert]::ToInt32(($SubnetBin[$i]),2) -eq [convert]::ToInt32(($IPBin[$i]),2)
    if ($diff -eq $false) {
        $Result = $diff
    }
}

$Result