IPAddress.Parse documentation inaccurate

D

dfrauzel

http://msdn2.microsoft.com/en-us/library/system.net.ipaddress.parse.aspx

.... states that you can call .Parse() with a single integral argument
(as a string); "A one part address is stored directly in the network
address." (The example in the table included states that 65536
converts to 0.0.255.255 - this is incorrect. 65535 is 0.0.255.255.
65536 is 0.1.0.0.)

The problem is, as with the IPAddress constructor itself, the argument
is expected to be in network-byte-order. Attempting to parse
4294967295 (or anything with a low-order value above 127) results in
an exception, because the processing involved is using an unsigned
integer (a long) and flipping a 32-bit address as-is puts your
significant bits on the wrong side of the 32-bit boundary.

Which means you can't rely on Parse with a single integral argument,
and even if you want to use the IPAddress constructor this way
(because, for example, you're doing some bitwise math using uints to
determine a network address and broadcast address from an adapter
address - the built-in .Broadcast is absolute rubbish), you'll have to
work around the network-byte-order expectation with some tedious
bitwise math:

private IPAddress LongToIP(long lip)
{
long htn = IPAddress.HostToNetworkOrder(lip);
htn >>= 32;
htn &= 0x00000000FFFFFFFF;

return new IPAddress(htn);
}

I think the documentation should be more clear about this, and what to
expect on various platforms. I also think the IPAddress class should
use strictly signed integers (there are no negative IP addresses),
though I suppose there may be some good rationale for that particular
decision.
 
D

dfrauzel

Done! The feedback at least. I hesitate to submit community content,
since it would hopefully be outdated before long!

But some discussion on the meaning of network-byte-order and host-byte-
order would be useful, I guess. Now look what I've got myself into.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top