ipnetwork
ipnetwork copied to clipboard
Feature Request: IPNetwork.FromSingleAddress(IPAddress)
I have an IPAddress value. Is there a simple way to produce an IPNetwork object that represents this single IP? (Implied /32 or /128 as applicable.)
A static function of IPNetwork, or an extension function adding ".AsNetwork" to IPAddress would do the job.
Many thanks.
Thanks for your feedback. I'll have a look at this if time permits.
- Create an System.Net.IPAddress object from your ip (either ipv4 or ipv6)
- Convert it to IPv6 using the MapToIPv6 function. Either it returns the same ipv6 address or it converts the ipv4 into an ipv6. Either way we get an IPv6 address out of it.
- Parse the IPAddress into an IPNetwork object with /128 as cidr suffix.
- Print the display Address (you should keep it as mapped address, until you need to display it somewhere for simplicity)
#powershell
$ipaddress = [System.Net.IPAddress]"192.168.2.1"
$versionIndependent = $ipaddress.MapToIPv6()
$ipnetworkObject = [System.Net.IPNetwork]::Parse($versionIndependent, [System.Net.IPAddress]"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")
$displayAddress = ($ipnetworkObject.Network.IsIPv4MappedToIPv6) ? $ipnetworkObject.Network.MapToIPv4().IPAddressToString : $ipnetworkObject.Network.IPAddressToString
Write-Host $displayAddress
I'd like to have an overload for Parse function like:
static System.Net.IPNetwork Parse(ipaddress ipaddress, int cidrSuffix)
so that I can specify the cidr Suffix as e.g. 128 instead of it's hexadecimal representation.