diff --git a/TechnitiumLibrary.Net/NetworkMap.cs b/TechnitiumLibrary.Net/NetworkMap.cs index 8c12473d..26f50f34 100644 --- a/TechnitiumLibrary.Net/NetworkMap.cs +++ b/TechnitiumLibrary.Net/NetworkMap.cs @@ -1,6 +1,7 @@ /* Technitium Library Copyright (C) 2024 Shreyas Zare (shreyas@technitium.com) +Copyright (C) 2026 Zafer Balkan (zafer@zaferbalkan.com) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -20,6 +21,7 @@ You should have received a copy of the GNU General Public License using System; using System.Collections.Generic; using System.Net; +using System.Net.Sockets; namespace TechnitiumLibrary.Net { @@ -28,6 +30,7 @@ public class NetworkMap #region variables readonly List _ipLookupList; + volatile AddressFamily _networkFamily = AddressFamily.Unspecified; bool _sorted; #endregion @@ -105,6 +108,16 @@ public void Add(NetworkAddress networkAddress, T value) { lock (_ipLookupList) { + // The first entry decides what kind of network map + // we are creating + if (_networkFamily == AddressFamily.Unspecified) + { + _networkFamily = networkAddress.AddressFamily; + } + else if (_networkFamily != networkAddress.AddressFamily) + { + throw new InvalidOperationException("Cannot add network address of different address family to the map."); + } _ipLookupList.Add(new IpEntry(networkAddress.Address, value)); _ipLookupList.Add(new IpEntry(networkAddress.GetLastAddress(), value)); @@ -121,10 +134,16 @@ public bool Remove(NetworkAddress networkAddress) { lock (_ipLookupList) { + if (networkAddress.AddressFamily != _networkFamily) + { + return false; + } + bool v1 = _ipLookupList.Remove(new IpEntry(networkAddress.Address)); bool v2 = _ipLookupList.Remove(new IpEntry(networkAddress.GetLastAddress())); _sorted = false; + return v1 & v2; } } @@ -136,6 +155,12 @@ public bool TryGetValue(string address, out T value) public bool TryGetValue(IPAddress address, out T value) { + if (address.AddressFamily != _networkFamily) + { + value = default; + return false; + } + if (!_sorted) { lock (_ipLookupList)