Skip to content

IPAddress static fields are readonly, but their values aren't #27870

@alfredmyers

Description

@alfredmyers

IPAddress static fields for Any, Broadcast, Local and None are marked readonly

https://github.com/dotnet/corefx/blob/b0b1452eaaa120dc8267ebbe5a93798f77ec5ed1/src/System.Net.Primitives/src/System/Net/IPAddress.cs#L20-L23

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions