Advertisement
AbduallahMohsen

Untitled

Mar 2nd, 2021
740
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.93 KB | None | 0 0
  1. using System;
  2. using System.Collections.Concurrent;
  3.  
  4. namespace GameServer.Networking
  5. {
  6.     public class SocketProtection
  7.     {
  8.         public ConcurrentDictionary<string, ConnectionInfo> Connections;
  9.         private readonly string Server;
  10.  
  11.         public SocketProtection(string server)
  12.         {
  13.             Connections = new ConcurrentDictionary<string, ConnectionInfo>(1, 100);
  14.             Server = server;
  15.         }
  16.         public bool IsBanned(string IP) => Connections.TryGetValue(IP, out ConnectionInfo connection) && connection.BannedTime > DateTime.Now;
  17.         public void Oversee(string IP)
  18.         {
  19.             if (Connections.TryGetValue(IP, out ConnectionInfo connection))
  20.             {
  21.                 if (DateTime.Now.AddSeconds(-1) > connection.LastConnection) connection.Count++;
  22.  
  23.                 connection.LastConnection = DateTime.Now;
  24.                 if (connection.Count >= 10)
  25.                 {
  26.                     Console.WriteLine($"{IP} Has been ban from {Server}.");
  27.                     connection.BannedTime = DateTime.Now.AddMinutes(1);
  28.                 }
  29.             }
  30.             else Connections.TryAdd(IP, new ConnectionInfo()
  31.             {
  32.                 BannedTime = DateTime.Now.AddSeconds(-1),
  33.                 IP = IP,
  34.                 LastConnection = DateTime.Now
  35.             });
  36.         }
  37.         public void CheckConnections()
  38.         {
  39.             foreach (var connection in Connections.Values)
  40.             {
  41.                 if (connection.BannedTime > DateTime.Now)
  42.                     continue;
  43.  
  44.                 if (DateTime.Now >= connection.LastConnection.AddMinutes(1))
  45.                     Connections.TryRemove(connection.IP, out _);
  46.             }
  47.         }
  48.         public class ConnectionInfo
  49.         {
  50.             public string IP;
  51.             public DateTime BannedTime;
  52.             public DateTime LastConnection;
  53.             public uint Count;
  54.         }
  55.  
  56.     }
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement