Search code examples
c#.netnetwork-programmingsignedness

Why does System.Net.IPAddress use signed types?


The methods IPAddress(Int64) and Int32 HostToNetworkOrder(Int32) in System.Net.IPAddress both uses signed types for IP addresses.

This makes it necessary to cast the result from HostToNetworkOrder when using it as a parameter to the IPAddress constructor, resulting in code such as this:

            UInt32 netOrderU32 = (UInt32)IPAddress.HostToNetworkOrder((Int32)ipVal);
            IPAddress tempIP = new IPAddress(netOrderU32);

If the network-order value is not unsigned, addresses such as 192.168.0.255 will cause ArgumentOutOfRangeException. Could this be caused by IPAddress(Int64) not accepting values lager than 0x00000000FFFFFFFF but the Int64 representation of (net-order)192.168.0.255 is 0xffffffffff00a8c0 when converting from Int32 ?

Is there any point in using signed types even though an IP address doesn't have any notion of signedness? It seems as if it would be much simpler to just use unsigned types.

Is there any specific reason why signed types where chosen?


Solution

  • It would seem that the choice to go with signed over unsigned in this case is because of how certain platforms handle signed vs unsigned numbers.

    This post sheds some light on the fact that .NET libraries and functions require the use of signed integers over unsigned so they can maintain portability with languages that do not provide an explicit unsigned type.

    This post goes into more detail about specifically why C# opted to use signed integers, because unsigned integers are not CLS compliant. Read even more about that here.

    Without a full picture of your specific application (and the need for byte-swapping) it's hard to tell if what you're doing here is actually problematic or not.