Saturday, September 7, 2013

SortedList Collection and IP Address generation

I spent this morning working with the SortedList Collection and IP Address generation. SortedList maintains an IDictionary interface to a Key/Value pair collection (see  Krivayakov ) The advantage is a simple and direct reference to the last octet for Class C subnet generation and reference: 

rv -ea 0 SN
$SN = new-object System.Collections.SortedList
foreach ($i in (0..254)) {$SN.add($i,[IPAddress]"192.168.0.$i")}

foreach ($i in (0..254)) {$SN.add($i,[IPAddress]"192.168.0.$i")}
PS C:\> $SN

Name Value
---- -----

PS C:\> ($SN[0])

Address : 43200
AddressFamily : InterNetwork
ScopeId :
IsIPv6Multicast : False
IsIPv6LinkLocal : False
IsIPv6SiteLocal : False
IsIPv6Teredo : False
IsIPv4MappedToIPv6 : False
IPAddressToString :

This makes collecting arbitrary IP ranges a simple reference to their Name/Key:

PS C:\Powershell> $b = ($SN[0,8,23]).IPAddressToString + ($SN[23..27]).IPAddressToString
PS C:\Powershell> $b

A little more complicated for multiple subnets:

rv -EA 0 SN0;rv -EA 0 SN1;rv -EA 0 SN2;
$SN0 = new-object System.Collections.SortedList
$SN1 = new-object System.Collections.SortedList
$SN2 = new-object System.Collections.SortedList
for ($i = 0; $i -ile 254;$i++){$SN0.add($i,[IPAddress]"192.168.0.$i")}
for ($i = 0; $i -ile 254;$i++){$SN1.add($i,[IPAddress]"192.168.1.$i")}
for ($i = 0; $i -ile 254;$i++){$SN2.add($i,[IPAddress]"192.168.2.$i")}

$c = ($SN0[0,8,23]).IPAddressToString + ($SN1[23..27]).IPAddressToString + ($SN2[148..154]).IPAddressToString

PS C:\> $c

1 comment:

Silvester Norman said...

It is one of the simplest methods through which MAC Address can be generated.Thanks for sharing.

Silvester Norman

Change MAC Address