Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does IPAddress sometimes throw an ArgumentOutOfRangeException?

Tags:

c#

I was just trying to debug the following exception:

Exception has been thrown by the target of an invocation.: System.Reflection.TargetInvocationException: 
Exception has been thrown by the target of an invocation. ---> 
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: newAddress
   at System.Net.IPAddress..ctor(Int64 newAddress)

This is the code in question:

int hostToNetworkOrder = IPAddress.HostToNetworkOrder( (int)computer.IpAddress );
IPAddress ipAddress = new IPAddress( hostToNetworkOrder );

computer.IpAddress is set to 1582281193. This gets converted to hostToNetworkOrder, which is -374255778.

Now, if I try to construct new IPAddress( -374255778 ); in the Immediate Window in Visual Studio, I get an IPAddress object containing the correct IP address.

But if I step over the line in the code, it will always throw an ArgumentOutOfRangeException. Why?


Update

I was aware that my input being negative was, most likely, the source of this issue. This is how I solved it:

UInt32 hostToNetworkOrder = (UInt32)IPAddress.HostToNetworkOrder( (Int32)computer.IpAddress );
IPAddress ipAddress = new IPAddress( hostToNetworkOrder );

What I still don't understand is why it worked at all in the Immediate Window.

like image 780
Oliver Salzburg Avatar asked Feb 02 '23 06:02

Oliver Salzburg


1 Answers

Looking at the IPAddress class in ILSpy there is an internal constructor that takes an int and does not do an argument out of range check - I have a feeling that it may be calling that constructor in the watch window but in the actual code it calls the public ctor(long), which does validate that number.

To test out my theory, I just tried this bit of code:

var ipAddress = (IPAddress) typeof (IPAddress)
                                        .GetConstructor(
                                            BindingFlags.NonPublic | BindingFlags.Instance,
                                            null,
                                            new[] {typeof (int)},
                                            null)
                                        .Invoke(new object[] {hostToNetworkOrder });

and, sure enough, the IPAddress class is constructed without error.

like image 173
kmp Avatar answered Mar 30 '23 00:03

kmp