Search code examples
powershellipv6cidr

Parsing IPv6 CIDR into first address and last address in Powershell


I'm trying to convert given IPv6 ranges supplied with CIDR notation into a range (first_address-last_address) in Powershell but am coming a bit unstuck.

A sample of the source data:

2a01:111:f406:c00::/64
2a01:111:f400:7c00::/54
2a01:111:f403::/48

Sample of required Output (doesn't need to be exact, i can mess with the format:

2a01:111:f406:c00::-2a01:111:f406:c00:ffff:ffff:ffff:ffff
2a01:111:f400:7c00::-2a01:111:f400:7fff:ffff:ffff:ffff:ffff
2a01:111:f403:0:0:0:0:0::-2a01:111:f403:ffff:ffff:ffff:ffff:ffff

I have googled extensively but not found anything that has pointed me in the right direction for powershell - I've found a php and js example but did't translate well.

Any pointers?

Thanks!


Solution

  • AFAIK, there's nothing in the BCL that parse IPv6 network segments - I would use the IPNetwork library (works with both IPv4 and 6):

    Add-Type -Path C:\path\to\System.Net.IPNetwork.dll
    
    # Parse ipv6/cidr string
    $Network = [System.Net.IPNetwork]::Parse('2a01:111:f400:7c00::/54')
    
    # Format string with first and last usable address
    $Range = '{0}-{1}' -f $Network.FirstUsable,$Network.LastUsable