-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathGetIPv4Subnet.psm1
495 lines (431 loc) · 11.8 KB
/
GetIPv4Subnet.psm1
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
function Convert-IPv4AddressToBinaryString
{
<#
.SYNOPSIS
Converts an IPv4 Address to Binary String
.PARAMETER IPAddress
The IP Address to convert to a binary string representation
.EXAMPLE
Convert-IPv4AddressToBinaryString -IPAddress 10.130.1.52
#>
Param(
[IPAddress]$IPAddress = '0.0.0.0'
)
$addressBytes = $IPAddress.GetAddressBytes()
$strBuilder = New-Object -TypeName Text.StringBuilder
foreach ($byte in $addressBytes)
{
$8bitString = [Convert]::ToString($byte, 2).PadLeft(8, '0')
$null = $strBuilder.Append($8bitString)
}
return $strBuilder.ToString()
}
function Get-IPv4Subnet
{
<#
.SYNOPSIS
Get information about an IPv4 subnet based on an IP Address and a subnet mask or prefix length
.DESCRIPTION
Get information about an IPv4 subnet based on an IP Address and a subnet mask or prefix length
.PARAMETER IPAddress
The IP Address to use for determining subnet information.
.PARAMETER PrefixLength
The prefix length of the subnet.
.PARAMETER SubnetMask
The subnet mask of the subnet.
.EXAMPLE
Get-IPv4Subnet -IPAddress 192.168.34.76 -SubnetMask 255.255.128.0
CidrID : 192.168.0.0/17
NetworkID : 192.168.0.0
SubnetMask : 255.255.128.0
PrefixLength : 17
HostCount : 32766
FirstHostIP : 192.168.0.1
LastHostIP : 192.168.127.254
Broadcast : 192.168.127.255
Description
-----------
This command will get the subnet information about the IPAddress 192.168.34.76, with the subnet mask of 255.255.128.0
.EXAMPLE
Get-IPv4Subnet -IPAddress 10.3.40.54 -PrefixLength 25
CidrID : 10.3.40.0/25
NetworkID : 10.3.40.0
SubnetMask : 255.255.255.128
PrefixLength : 25
HostCount : 126
FirstHostIP : 10.3.40.1
LastHostIP : 10.3.40.126
Broadcast : 10.3.40.127
Description
-----------
This command will get the subnet information about the IPAddress 10.3.40.54, with the subnet prefix length of 25.
Prefix length specifies the number of bits in the IP address that are to be used as the subnet mask.
#>
[CmdletBinding(DefaultParameterSetName = 'PrefixLength')]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
ValueFromRemainingArguments = $false,
HelpMessage = 'IP Address in the form of XXX.XXX.XXX.XXX',
Position = 0
)]
[IPAddress]$IPAddress
,
[Parameter(
Position = 1,
ParameterSetName = 'PrefixLength',
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)]
[Int16]$PrefixLength = 24
,
[Parameter(Mandatory = $true, Position = 1, ParameterSetName = 'SubnetMask')]
[IPAddress]$SubnetMask
,
[Parameter(
Mandatory = $true,
Position = 1,
ParameterSetName = 'Hosts',
HelpMessage = 'Number of hosts in need of IP Addresses'
)]
[Int64]$HostCount
)
begin
{
}
process
{
try
{
if ($PSCmdlet.ParameterSetName -eq 'SubnetMask')
{
$PrefixLength = Convert-NetMaskToCIDR -SubnetMask $SubnetMask `
-ErrorAction Stop
}
else
{
$SubnetMask = Convert-CIDRToNetMask -PrefixLength $PrefixLength `
-ErrorAction Stop
}
if ($PSCmdlet.ParameterSetName -eq 'Hosts')
{
$PrefixLength = (Get-CidrFromHostCount -HostCount $HostCount).PrefixLength
$SubnetMask = Convert-CIDRToNetMask -PrefixLength $PrefixLength `
-ErrorAction Stop
}
$maxHosts = [math]::Pow(2, (32 - $PrefixLength)) - 2
$netMaskInt = ConvertIPv4ToInt -IPv4Address $SubnetMask
$ipInt = ConvertIPv4ToInt -IPv4Address $IPAddress
$networkID = ConvertIntToIPv4 -Integer ($netMaskInt -band $ipInt)
$broadcast = Add-IntToIPv4Address -IPv4Address $networkID `
-Integer ($maxHosts + 1)
$firstIP = Add-IntToIPv4Address -IPv4Address $networkID -Integer 1
$lastIP = Add-IntToIPv4Address -IPv4Address $broadcast -Integer (-1)
if ($PrefixLength -eq 32)
{
$broadcast = $networkID
$firstIP = $null
$lastIP = $null
$maxHosts = 0
}
$outputObject = New-Object -TypeName PSObject
$memberParam = @{
InputObject = $outputObject
MemberType = 'NoteProperty'
Force = $true
}
Add-Member @memberParam -Name CidrID -Value ('{0}/{1}' -f $networkID, $PrefixLength)
Add-Member @memberParam -Name NetworkID -Value $networkID
Add-Member @memberParam -Name SubnetMask -Value $SubnetMask
Add-Member @memberParam -Name PrefixLength -Value $PrefixLength
Add-Member @memberParam -Name HostCount -Value $maxHosts
Add-Member @memberParam -Name FirstHostIP -Value $firstIP
Add-Member @memberParam -Name LastHostIP -Value $lastIP
Add-Member @memberParam -Name Broadcast -Value $broadcast
Write-Output -InputObject $outputObject
}
catch
{
Write-Error -Exception $_.Exception `
-Category $_.CategoryInfo.Category
}
}
}
function Add-IntToIPv4Address
{
<#
.SYNOPSIS
Add an integer to an IP Address and get the new IP Address.
.DESCRIPTION
Add an integer to an IP Address and get the new IP Address.
.PARAMETER IPv4Address
The IP Address to add an integer to.
.PARAMETER Integer
An integer to add to the IP Address. Can be a positive or negative number.
.EXAMPLE
Add-IntToIPv4Address -IPv4Address 10.10.0.252 -Integer 10
10.10.1.6
Description
-----------
This command will add 10 to the IP Address 10.10.0.1 and return the new IP Address.
.EXAMPLE
Add-IntToIPv4Address -IPv4Address 192.168.1.28 -Integer -100
192.168.0.184
Description
-----------
This command will subtract 100 from the IP Address 192.168.1.28 and return the new IP Address.
#>
param(
[Parameter(Mandatory = $true)]
[String]$IPv4Address
,
[Parameter(Mandatory = $true)]
[int64]$Integer
)
try
{
$ipInt = ConvertIPv4ToInt -IPv4Address $IPv4Address `
-ErrorAction Stop
$ipInt += $Integer
return (ConvertIntToIPv4 -Integer $ipInt)
}
catch
{
Write-Error -Exception $_.Exception `
-Category $_.CategoryInfo.Category
}
}
function Convert-CIDRToNetMask
{
<#
.SYNOPSIS
Converts a CIDR to a netmask
.EXAMPLE
Convert-CIDRToNetMask -PrefixLength 26
Returns: 255.255.255.192/26
.NOTES
To convert back use "Convert-NetMaskToCIDR"
#>
[CmdletBinding()]
[Alias('ToMask')]
param(
[ValidateRange(0, 32)]
[int16]$PrefixLength = 0
)
$bitString = ('1' * $PrefixLength).PadRight(32, '0')
$strBuilder = New-Object -TypeName Text.StringBuilder
for ($i = 0; $i -lt 32; $i += 8)
{
$8bitString = $bitString.Substring($i, 8)
$null = $strBuilder.Append(('{0}.' -f [Convert]::ToInt32($8bitString, 2)))
}
return $strBuilder.ToString().TrimEnd('.')
}
function Convert-NetMaskToCIDR
{
<#
.SYNOPSIS
Converts a netmask to a CIDR
.EXAMPLE
Convert-NetMaskToCIDR -SubnetMask 255.255.255.192
Returns: 26
.NOTES
To convert back use "Convert-CIDRToNetMask"
#>
[CmdletBinding()]
[Alias('ToCIDR')]
param(
[String]$SubnetMask = '255.255.255.0'
)
$byteRegex = '^(0|128|192|224|240|248|252|254|255)$'
$invalidMaskMsg = ('Invalid SubnetMask specified [{0}]' -f $SubnetMask)
try
{
$netMaskIP = [IPAddress]$SubnetMask
$addressBytes = $netMaskIP.GetAddressBytes()
$strBuilder = New-Object -TypeName Text.StringBuilder
$lastByte = 255
foreach ($byte in $addressBytes)
{
# Validate byte matches net mask value
if ($byte -notmatch $byteRegex)
{
Write-Error -Message $invalidMaskMsg `
-Category InvalidArgument `
-ErrorAction Stop
}
elseif ($lastByte -ne 255 -and $byte -gt 0)
{
Write-Error -Message $invalidMaskMsg `
-Category InvalidArgument `
-ErrorAction Stop
}
$null = $strBuilder.Append([Convert]::ToString($byte, 2))
$lastByte = $byte
}
return ($strBuilder.ToString().TrimEnd('0')).Length
}
catch
{
Write-Error -Exception $_.Exception `
-Category $_.CategoryInfo.Category
}
}
function Get-CidrFromHostCount
{
<#
.SYNOPSIS
Returns the CIDR number for a host count that will support the number of hosts you entered.
#>
[OutputType([Int])]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
HelpMessage = 'Integer between 1 - 4294967293'
)]
[UInt32]$HostCount
)
begin
{
}
process
{
#Calculate available host addresses
$i = $maxHosts = 0
$prefix = 32
while ($maxHosts -lt $HostCount)
{
if ($HostCount -eq 0)
{
break
}
elseif ($i -eq 32)
{
break
}
$i++
$maxHosts = ([math]::Pow(2, $i) - 2)
$prefix = 32 - $i
}
$prefixLength = [PSCustomObject]@{
PrefixLength = $prefix;
}
return $prefixLength
}
}
function Get-SubnetCheatSheet
{
<#
.SYNOPSIS
Creates a little cheatsheet for subnets.
.DESCRIPTION
Creates and send a cheatsheet for subnets to the console or send it to a file such as a CSV for opening in a spreadsheet.
The default is formated for the console.
.PARAMETER Raw
Use this parameter to output an object for more manipulation
.EXAMPLE
Get-SubnetCheatSheet
.EXAMPLE
Get-SubnetCheatSheet -Raw | Where-Object {($_.CIDR -gt 15) -and ($_.CIDR -lt 22)} | Select-Object CIDR,Netmask
.EXAMPLE
Get-SubnetCheatSheet -Raw | Export-Csv .\SubnetSheet.csv -NoTypeInformation
Sends the data to a csv file
.EXAMPLE
Get-SubnetCheatSheet -Raw | Where-Object {$_.NetMask -like '255.255.*.0' }
Selects only one class of subnets
.Example
Get-SubnetCheatSheet | Out-Printer -Name (Get-Printer | Out-GridView -PassThru).Name
#>
[CmdletBinding()]
[Alias('SubnetList', 'ListSubnets')]
param(
[Switch]$Raw
)
begin
{
$OutputFormatting = '{0,4} | {1,13:#,#} | {2,13:#,#} | {3,-15} '
$CheatSheet = @()
}
process
{
for($CIDR = 32;$CIDR -gt 0;$CIDR--)
{
$netmask = Convert-CIDRToNetMask -PrefixLength $CIDR
$Addresses = [math]::Pow(2,32-$CIDR)
$HostCount = (&{
if($Addresses -le 2)
{
'0'
}
else
{
$Addresses -2
}
})
$hash = [PsCustomObject]@{
CIDR = $CIDR
NetMask = $netmask
HostCount = $HostCount
Addresses = $Addresses
}
$CheatSheet += $hash
}
}
end
{
if(-not $Raw)
{
$OutputFormatting -f 'CIDR', 'Host Count', 'Addresses', 'NetMask'
'='*55
foreach($item in $CheatSheet)
{
$OutputFormatting -f $item.CIDR, $item.HostCount, $item.Addresses, $item.NetMask
}
}
else
{
$CheatSheet
}
}
}
# Non-Published Functions
function ConvertIPv4ToInt
{
[CmdletBinding()]
param(
[String]$IPv4Address
)
try
{
$ipAddress = [IPAddress]::Parse($IPv4Address)
$bytes = $IPAddress.GetAddressBytes()
[Array]::Reverse($bytes)
return [BitConverter]::ToUInt32($bytes, 0)
}
catch
{
Write-Error -Exception $_.Exception `
-Category $_.CategoryInfo.Category
}
}
function ConvertIntToIPv4
{
[CmdletBinding()]
param(
[uint32]$Integer
)
try
{
$bytes = [BitConverter]::GetBytes($Integer)
[Array]::Reverse($bytes)
([IPAddress]($bytes)).ToString()
}
catch
{
Write-Error -Exception $_.Exception `
-Category $_.CategoryInfo.Category
}
}