80 lines
2.1 KiB
C#
80 lines
2.1 KiB
C#
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Net;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace GsDChat.Server.Services;
|
|
|
|
public class ConnectionLimiterService
|
|
{
|
|
private readonly ConcurrentDictionary<string, int> _ipConnections = new();
|
|
private readonly int _maxConnectionsPerIp;
|
|
private readonly int _maxGlobalConnections;
|
|
private int _globalConnectionCount;
|
|
|
|
public ConnectionLimiterService(int maxConnectionsPerIp = 10, int maxGlobalConnections = 100)
|
|
{
|
|
_maxConnectionsPerIp = maxConnectionsPerIp;
|
|
_maxGlobalConnections = maxGlobalConnections;
|
|
}
|
|
|
|
public bool TryAddConnection(string ipAddress)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(ipAddress))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
lock (this)
|
|
{
|
|
if (_globalConnectionCount >= _maxGlobalConnections)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var currentIpCount = _ipConnections.GetOrAdd(ipAddress, 0);
|
|
if (currentIpCount >= _maxConnectionsPerIp)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
_ipConnections.AddOrUpdate(ipAddress, 1, (_, existing) => existing + 1);
|
|
_globalConnectionCount++;
|
|
return true;
|
|
}
|
|
}
|
|
|
|
public void RemoveConnection(string ipAddress)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(ipAddress))
|
|
{
|
|
return;
|
|
}
|
|
|
|
lock (this)
|
|
{
|
|
if (_ipConnections.TryGetValue(ipAddress, out var count))
|
|
{
|
|
if (count <= 1)
|
|
{
|
|
_ipConnections.TryRemove(ipAddress, out _);
|
|
}
|
|
else
|
|
{
|
|
_ipConnections.AddOrUpdate(ipAddress, 0, (_, existing) => existing - 1);
|
|
}
|
|
_globalConnectionCount = Math.Max(0, _globalConnectionCount - 1);
|
|
}
|
|
}
|
|
}
|
|
|
|
public int GetConnectionCount(string ipAddress)
|
|
{
|
|
return _ipConnections.TryGetValue(ipAddress, out var count) ? count : 0;
|
|
}
|
|
|
|
public int GetGlobalConnectionCount()
|
|
{
|
|
return _globalConnectionCount;
|
|
}
|
|
}
|