How to implement below functionality in C# RRS feed

  • Question

  • Hi All,

    I need some help to implement below functionality using C# code,

    1. I need to convert IPv6 Address to Long

    2. Convert Long value to IPv6 Address.

    3. How to convert IPv6 Address Mask to Long value

    4. How to convert Long value to IPv6 Address Mask

    I tried in different ways but I can't get expected output. Please provide your idea or thoughts to implement above mentioned 4 functionality.


    • Moved by Bill_Stewart Monday, July 7, 2014 7:05 PM Abandoned poor quality question (someone write code for me)
    Thursday, March 27, 2014 1:12 PM

All replies

  • Use System.Net.IPAddress class.

    PS C:\scripts> $addr=[ipaddress]''
    PS C:\scripts> $addr.Address
    PS C:\scripts> $addr=[ipaddress]'2001:0:9d38:90d7:10fe:70d:bbdb:417'
    PS C:\scripts> $addr.Address
    PS C:\scripts> $addr


    Thursday, March 27, 2014 1:26 PM
  • Long is a 64-bit number; IPv6 addresses are 128-bit numbers.  You can't convert an IPv6 address to "long".

    Also, the Address property, for whatever reason, gives you the address bytes in little-endian order, which is basically useless for most IP math (masking, etc.)  As a result, I use this function to convert IPv4 addresses to UInt32 values in PowerShell.  You should be able to use a similar approach for IPv6 addresses using a numeric type that can hold a 128-bit value (probably BigInteger):

    function Convert-IPAddressToUInt32([ipaddress] $IPAddress)
        if ($IPAddress.AddressFamily -ne [System.Net.Sockets.AddressFamily]::InterNetwork)
            throw "$($IPAddress.IPAddressToString) is not an IPv4 address."
        $bytes = $IPAddress.GetAddressBytes()
        if ([System.BitConverter]::IsLittleEndian)
        return [System.BitConverter]::ToUInt32($bytes, 0)

    • Edited by David Wyatt Thursday, March 27, 2014 2:08 PM
    Thursday, March 27, 2014 2:07 PM
  • System.Net.IPAddress correctly converts IPV4Addresses. IPV6Addresses make no sense as integers.

    The main use to an in in IPV4 as an int is to extract or compare subnets.  IPV8 sub-netting is not like IPV4.


    Thursday, March 27, 2014 2:15 PM
  • System.Net.IPAddress correctly converts IPV4Addresses.

    No, it doesn't.  Using the function I posted as an example:

    $ip = [ipaddress]''
    (Convert-IPAddressToUInt32 $ip).ToString("X8")

    I don't know why the IPAddress.Address property gives you the little-endian version.  You can't really do any useful subnet math with that.
    Thursday, March 27, 2014 2:26 PM
  • The subnet address calculations are based on this integer version.  They work correctly when used in subnetting algoritms.  It is not intended to be an integer representation of an IP.

    Remember that a subnet is a mask.  It is used as a mask and not as a number.

    I will see if I can find some old subnetting scripts based on this number.


    Thursday, March 27, 2014 2:33 PM