Skip to content
Closed
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions TechnitiumLibrary.Net/NetworkMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,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
{
Expand All @@ -28,6 +29,7 @@ public class NetworkMap<T>
#region variables

readonly List<IpEntry> _ipLookupList;
volatile AddressFamily _networkFamily = AddressFamily.Unspecified;
bool _sorted;

#endregion
Expand Down Expand Up @@ -105,6 +107,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.");
}
Comment thread
zbalkan marked this conversation as resolved.
_ipLookupList.Add(new IpEntry(networkAddress.Address, value));
_ipLookupList.Add(new IpEntry(networkAddress.GetLastAddress(), value));

Expand All @@ -121,10 +133,17 @@ 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;

if (_ipLookupList.Count == 0) _networkFamily = AddressFamily.Unspecified; // reset internal address family, class may be reused.
Comment thread
zbalkan marked this conversation as resolved.
Outdated
return v1 & v2;
}
}
Expand All @@ -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;
}
Comment thread
zbalkan marked this conversation as resolved.

if (!_sorted)
{
lock (_ipLookupList)
Expand Down