1

I have an IPv6 address provided as a byte[16] array and I would like to convert it to string (for the purpose of logging).

I would normally achieve this in C# using the System.Net.IPAddress constructor, but it seems that System.Net.IPAddress is not available in C# for WinRT/Windows Store. Does anyone have an equivalent way to do this conversion/formatting?

1
  • Oh and I know there is a very long way to do this (by looking up the .NET reflector code for IPAddress.ToString()) and seeing how MS handles this internally) but i'm hoping to find something already built-in to C#. Commented Feb 27, 2014 at 8:41

3 Answers 3

1

Converting a byte array to a valid IPv6 address is easy enough.

// Precondition: bytes.Length == 16
string ConvertToIPv6Address(byte[] bytes)
{
    var str = new StringBuilder();
    for (var i = 0; i < bytes.Length; i+=2)
    {
        var segment = (ushort)bytes[i] << 8 | bytes[i + 1];         
        str.AppendFormat("{0:X}", segment);
        if (i + 2 != bytes.Length)
        {
            str.Append(':');
        }           
    }

    return str.ToString();
}

Collapsing empty segments is a little more involved, but generally not needed for anything other than display purposes.

Sign up to request clarification or add additional context in comments.

Comments

0

I believe Windows.Networking.HostName is the replacement for IPAddress.

Edit: But I'm not sure that you can create one from a byte[].

See also:

1 Comment

Thanks, I had also looked at Windows.Networking.Hostname - but i'm still not clear how to take this byte array and end up with a string representation of the IPv6 address :( This was a lot easier with System.Net.IPAddress
0

I solved this manually by just creating the full IPv6 string two bytes at a time with colon seperator. Then, I passed that string to Windows.Networking.HostName and accessed it's DisplayName property, which gave me back the compressed version (i.e. 0000 replaced with 0 and with a single :: replacement if applicable).

At least HostName saved me some of the work :) It's still a shame that there isn't a full IPAddress replacement though :(

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.