-
Notifications
You must be signed in to change notification settings - Fork 6.5k
Expand file tree
/
Copy pathTest-IpInRange.ps1
More file actions
53 lines (48 loc) · 1.71 KB
/
Test-IpInRange.ps1
File metadata and controls
53 lines (48 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function Test-IpInRange {
<#
.SYNOPSIS
Test if an IP address is in a CIDR range
.DESCRIPTION
This function tests if an IP address is in a CIDR range
.PARAMETER IPAddress
The IP address to test
.PARAMETER Range
The CIDR range to test
.EXAMPLE
Test-IpInRange -IPAddress "1.1.1.1" -Range "1.1.1.1/24"
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$IPAddress,
[Parameter(Mandatory = $true)]
[string]$Range
)
function ConvertIpToBigInteger {
param([System.Net.IPAddress]$ip)
return [System.Numerics.BigInteger]::Parse(
[BitConverter]::ToString($ip.GetAddressBytes()).Replace('-', ''),
[System.Globalization.NumberStyles]::HexNumber
)
}
try {
$IP = [System.Net.IPAddress]::Parse($IPAddress)
$rangeParts = $Range -split '/'
$networkAddr = [System.Net.IPAddress]::Parse($rangeParts[0])
$maxBits = if ($networkAddr.AddressFamily -eq 'InterNetworkV6') { 128 } else { 32 }
$prefix = if ($rangeParts.Count -gt 1) { [int]$rangeParts[1] } else { $maxBits }
if ($networkAddr.AddressFamily -ne $IP.AddressFamily) {
return $false
}
$ipBig = ConvertIpToBigInteger $IP
$netBig = ConvertIpToBigInteger $networkAddr
$shift = $maxBits - $prefix
$mask = [System.Numerics.BigInteger]::Pow(2, $shift) - [System.Numerics.BigInteger]::One
$invertedMask = [System.Numerics.BigInteger]::MinusOne -bxor $mask
$ipMasked = $ipBig -band $invertedMask
$netMasked = $netBig -band $invertedMask
return $ipMasked -eq $netMasked
} catch {
return $false
}
}