Skip to content

Commit 55bd0c6

Browse files
authored
Add network change detection to clear cached addresses. (#1456)
1 parent b682f2b commit 55bd0c6

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

src/sys/Net/NetServices.cs

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -97,20 +97,29 @@ public static bool SupportsDualModeIPv4PacketInfo
9797
/// A lookup collection to cache the local IP address for a destination address. The collection will cache results of
9898
/// asking the Operating System which local address to use for a destination address. The cache saves a relatively
9999
/// expensive call to create a socket and ask the OS for a route lookup.
100-
///
101-
/// TODO: Clear this cache if the state of the local network interfaces change.
102100
/// </summary>
103101
private static ConcurrentDictionary<IPAddress, Tuple<IPAddress, DateTime>> m_localAddressTable =
104102
new ConcurrentDictionary<IPAddress, Tuple<IPAddress, DateTime>>();
105103

104+
static NetServices()
105+
{
106+
NetworkChange.NetworkAddressChanged += (_, _) =>
107+
{
108+
// Clear cached addresses if the state of the local network interfaces change.
109+
m_localAddressTable.Clear();
110+
_localIPAddresses = null;
111+
_internetDefaultAddress = null;
112+
_internetDefaultIPv6Address = null;
113+
};
114+
}
115+
106116
/// <summary>
107117
/// The list of IP addresses that this machine can use.
108118
/// </summary>
109119
public static List<IPAddress> LocalIPAddresses
110120
{
111121
get
112122
{
113-
// TODO: Reset if the local network interfaces change.
114123
if (_localIPAddresses == null)
115124
{
116125
_localIPAddresses = NetServices.GetAllLocalIPAddresses();
@@ -133,7 +142,6 @@ public static IPAddress InternetDefaultAddress
133142
{
134143
get
135144
{
136-
// TODO: Reset if the local network interfaces change.
137145
if (_internetDefaultAddress == null)
138146
{
139147
_internetDefaultAddress = GetLocalAddressForInternet();
@@ -151,7 +159,6 @@ public static IPAddress InternetDefaultIPv6Address
151159
{
152160
get
153161
{
154-
// TODO: Reset if the local network interfaces change.
155162
if (_internetDefaultIPv6Address == null)
156163
{
157164
_internetDefaultIPv6Address = GetLocalIPv6AddressForInternet();

0 commit comments

Comments
 (0)