IPAddress.ToString expected to return a.b.c.d but returns d.c.b.a

I have a function from a third party vendor which returns an IPAddress in the form of a VB.NET UInteger. I am trying to convert this into the dotted decimal form by doing the following:

Dim oAddress as New System.Net.IPAddress([IP in UInteger form])

Dim sAddress as String = oAddress.ToString

I would expect the above to work, but where I am expecting to see "10.1.0.21", what I am getting is "21.0.1.10". Am I not using this right?

[486 byte] By [vbmon] at [2007-12-24]
# 1
IP-addresses in binary format are stored in an unusual, non-Intel CPU compatible way called BigEndian. The bytes are in reversed order. If the 3rd party vendor gives you the address stored in an UInteger, you better watch out for software quality issues.

You can swap the bytes in the proper order with the BitConverter class. Try something like this:

Private Function FixVendorAddress(ByVal addr As UInteger) As System.Net.IPAddress
Dim bytes() As Byte = BitConverter.GetBytes(addr)
Dim tmp As Byte
tmp = bytes(0)
bytes(0) = bytes(3)
bytes(3) = tmp
tmp = bytes(1)
bytes(1) = bytes(2)
bytes(2) = tmp
Return New System.Net.IPAddress(BitConverter.ToInt32(bytes, 0))
End Function

nobugz at 2007-8-31 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 2

And while nobugz snippet elegantly shows what needs to be done, you may want to consider using the framework's IpAddress.NetworkToHostOrder function to accomplish this instead .

Best regards,
Johan Stenberg

MSJohanStenberg at 2007-8-31 > top of Msdn Tech,Visual Basic,Visual Basic General...