Yury Schkatula
Yury Schkatula

Reputation: 5369

IPv6: Why changing ScopeId of System.Net.IPAddress is not reflected at ToString() representation?

Yesterday I met a thing that seems as a .NET bug.

IPAddress addr = IPAddress.Parse("fe80::1111:2222:abc%11"); // ScopeId is 11

string s1 = addr.ToString(); // I obviously see fe80::1111:2222:abc%11
addr.ScopeId = 0; // ScopeId is zero from now
string s2 = addr.ToString(); // I expect to see fe80::1111:2222:abc

Why s1 is the same content as s2 even after the ScopeId is changed? In debugger Watch window I see that scope value is really changed. But internal string field has no impact.

For sure, I tried this with various IPv6 addresses and different scope IDs - behavior is the same. What have I missed?

Upvotes: 4

Views: 1456

Answers (1)

user392139
user392139

Reputation: 116

I would call this a bug in the .NET Framework.

If you look at the source code for the IPAddress class:

http://referencesource.microsoft.com/#System/net/System/Net/IPAddress.cs

You'll see that the .ToString() method actually caches the results to a private field called m_ToString. However, if you then look at the setter for the ScopeId property, you see that it changes the private fields for m_ScopeId and m_Address, but it does not clear the m_ToString value.

If you look at the Address property, you'll see that they clear the m_ToString field when that property is set.

If you want a work around, you can do what they did here:

How do you determine equality between two IPv6 addresses?

by using the .GetAddressBytes() method to pass to the constructor to create a new instance. This will give you a ScopeId of zero.

Upvotes: 2

Related Questions