Fix subnet contains check

We are still using `Subnet.Contains` a lot but that does not handle IPv4 mapped to IPv6 addresses at all. It was partially fixed by #12094 in local network checking, but it may not always happen on LAN.

Also make all local network checking to use IsInLocalNetwork method instead of just performing `Subnet.Contains` which is not accurate.

Filter out all link-local addresses for external interface matching.
This commit is contained in:
gnattu
2025-02-04 16:52:17 +08:00
parent d376b5fbc7
commit 533ceeaaf2
2 changed files with 38 additions and 23 deletions

View File

@@ -326,4 +326,23 @@ public static partial class NetworkUtils
return new IPAddress(BitConverter.GetBytes(broadCastIPAddress));
}
/// <summary>
/// Check if a subnet contains an address. This method also handles IPv4 mapped to IPv6 addresses.
/// </summary>
/// <param name="network">The <see cref="IPNetwork"/>.</param>
/// <param name="address">The <see cref="IPAddress"/>.</param>
/// <returns>Whether the supplied IP is in the supplied network.</returns>
public static bool SubNetContainsAddress(IPNetwork network, IPAddress address)
{
ArgumentNullException.ThrowIfNull(address);
ArgumentNullException.ThrowIfNull(network);
if (address.IsIPv4MappedToIPv6)
{
address = address.MapToIPv4();
}
return network.Contains(address);
}
}