3

I have a IPv4 address provided as a uint 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?

Thank you.

Saghir A. Khatri
  • 3,429
  • 6
  • 45
  • 76
DaveUK
  • 1,440
  • 3
  • 18
  • 31

1 Answers1

4

A little "dirty", but seems to work

        uint ip = 0xFFDF5F4F;
        var bytes = BitConverter.GetBytes(ip);
        string res = string.Join(".", bytes.Reverse());

Output is 255.223.95.79 for this case

Jurion
  • 1,230
  • 11
  • 18
  • Works for me - thanks! (except my IP was already in host order so I just removed the reverse()) – DaveUK Feb 27 '14 at 05:13
  • Should the same work for IPv6 addresses stored as uint? (if . is changed for :) – DaveUK Feb 27 '14 at 05:44
  • By definition, you can not store Ipv6 address as uint :) unit has only 4 bytes. And I'm not sure it will work even with long or Int64. Ipv6 are not coded the same way – Jurion Feb 27 '14 at 05:44
  • Lol, sorry my bad...yes, I have the IPv6 address stored in a byte[16]. Usually I would pass that byte array into System.Net.IPAddress constructor. Any tips on how to get that byte array formatted as a IPv6 address string without System.Net.IPAddress ? :) – DaveUK Feb 27 '14 at 06:03
  • You can try the same method, but I really don't know what the result will be :) Take just last line. But I think ipv6 is not formatted byte by byte – Jurion Feb 27 '14 at 06:06
  • Ok thanks...this doesn't seem to work (as you suspected). This might become my next question on stackoverflow :) – DaveUK Feb 27 '14 at 06:14