Skip to content
Open
Changes from all 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
@@ -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
Expand All @@ -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
{
Expand All @@ -28,6 +30,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 +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));

Expand All @@ -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;
}
}
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;
}

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