Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 10dc9a2

Browse files
nil4stephentoub
authored andcommitted
Make well-known IPv4 addresses readonly (#33531)
* Fix https://github.com/dotnet/corefx/issues/33373 Use approach suggested in #33476 * Skip tests for IPAddress.Address setter throwing on .NET Framework
1 parent 4b9db6c commit 10dc9a2

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

src/System.Net.Primitives/src/System/Net/IPAddress.cs

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ namespace System.Net
1717
/// </devdoc>
1818
public class IPAddress
1919
{
20-
public static readonly IPAddress Any = new IPAddress(0x0000000000000000);
21-
public static readonly IPAddress Loopback = new IPAddress(0x000000000100007F);
22-
public static readonly IPAddress Broadcast = new IPAddress(0x00000000FFFFFFFF);
20+
public static readonly IPAddress Any = new ReadOnlyIPAddress(0x0000000000000000);
21+
public static readonly IPAddress Loopback = new ReadOnlyIPAddress(0x000000000100007F);
22+
public static readonly IPAddress Broadcast = new ReadOnlyIPAddress(0x00000000FFFFFFFF);
2323
public static readonly IPAddress None = Broadcast;
2424

2525
internal const long LoopbackMask = 0x00000000000000FF;
@@ -532,6 +532,10 @@ public long Address
532532
{
533533
if (PrivateAddress != value)
534534
{
535+
if (this is ReadOnlyIPAddress)
536+
{
537+
throw new SocketException(SocketError.OperationNotSupported);
538+
}
535539
PrivateAddress = unchecked((uint)value);
536540
}
537541
}
@@ -658,5 +662,11 @@ public IPAddress MapToIPv4()
658662
}
659663

660664
private static byte[] ThrowAddressNullException() => throw new ArgumentNullException("address");
665+
666+
private sealed class ReadOnlyIPAddress : IPAddress
667+
{
668+
public ReadOnlyIPAddress(long newAddress) : base(newAddress)
669+
{ }
670+
}
661671
}
662672
}

src/System.Net.Primitives/tests/FunctionalTests/IPAddressTest.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,16 @@ public static void Address_Property_Success()
311311
Assert.Equal(ip1, ip2);
312312
Assert.Equal(ip1.GetHashCode(), ip2.GetHashCode());
313313
}
314+
315+
[Fact]
316+
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // IPAddress.Value can be set on full framework
317+
public static void Address_ReadOnlyStatics_Set_Failure()
318+
{
319+
Assert.Throws<SocketException>(() => IPAddress.Any.Address = MaxAddress - 1);
320+
Assert.Throws<SocketException>(() => IPAddress.Broadcast.Address = MaxAddress - 1);
321+
Assert.Throws<SocketException>(() => IPAddress.Loopback.Address = MaxAddress - 1);
322+
Assert.Throws<SocketException>(() => IPAddress.None.Address = MaxAddress - 1);
323+
}
314324
#pragma warning restore 618
315325
}
316326
}

0 commit comments

Comments
 (0)