-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
IPAddress
static fields for Any
, Broadcast
, Local
and None
are marked readonly
Because of that, one could take for granted that they would always correspond to respectively 0.0.0.0
, 255.255.255.255
, 127.0.0.1
and 255.255.255.255
.
The thing is, it is possible to change their values through the obsoleted IPAddress.Address
property such as in
using System;
using System.Net;
class Program
{
static void Main()
{
Console.WriteLine("Well known IP addresses");
Write("Any", IPAddress.Any);
Write("Broadcast", IPAddress.Broadcast);
Write("Loopback", IPAddress.Loopback);
Write("None", IPAddress.None);
Console.WriteLine();
IPAddress.Any.Address = uint.MaxValue;
IPAddress.Broadcast.Address = 0;
IPAddress.Loopback.Address = IPAddress.Any.Address;
Console.WriteLine("Well known IP addresses. Or are they?");
Write("Any", IPAddress.Any);
Write("Broadcast", IPAddress.Broadcast);
Write("Loopback", IPAddress.Loopback);
Write("None", IPAddress.None);
Console.ReadKey();
void Write(string name, IPAddress address)
{
Console.WriteLine($"{name}\t{address}");
}
}
}
Output:
Well known IP addresses
Any 0.0.0.0
Broadcast 255.255.255.255
Loopback 127.0.0.1
None 255.255.255.255
Well known IP addresses. Or are they?
Any 255.255.255.255
Broadcast 0.0.0.0
Loopback 255.255.255.255
None 0.0.0.0
Although unexpected, it's quite easy to spot what is being done in the sample code above. But given the scope of static members, a troubleshooter may spend a couple of hours before realizing that any piece of code running in the process (or the AppDomain in case of the .NET Framework), including external dependencies (which would have generated warnings during compilation for members or types marked with [ObsoleteAttribute]
) could have changed the values of those fields.
The property has been obsoleted since .NET Framework 1.1 but is still lingering around and has been brought into .NET Core in 2.0 and into the .NET Standard 2.0 as well.
Given the pervasive use of these fields inside the .NET Core, it would be prudent to put safeguards in place to minimize the chance that their values are changed.