Reputation: 1580
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?
Upvotes: 1
Views: 1360
Reputation: 14088
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.
Upvotes: 1
Reputation: 1580
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 :(
Upvotes: 0
Reputation: 137398
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:
Upvotes: 0