fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5.  
  6. public class DDoSDetector
  7. {
  8. private Dictionary<IPAddress, List<DateTime>> requestLog;
  9. private readonly int threshold;
  10. private readonly TimeSpan timeWindow;
  11.  
  12. public DDoSDetector(int requestThreshold = 100, int timeWindowSeconds = 60)
  13. {
  14. requestLog = new Dictionary<IPAddress, List<DateTime>>();
  15. threshold = requestThreshold;
  16. timeWindow = TimeSpan.FromSeconds(timeWindowSeconds);
  17. }
  18.  
  19. public bool IsAttackDetected(IPAddress ipAddress)
  20. {
  21. var now = DateTime.UtcNow;
  22. if (!requestLog.ContainsKey(ipAddress))
  23. {
  24. requestLog[ipAddress] = new List<DateTime>();
  25. }
  26. requestLog[ipAddress].Add(now);
  27.  
  28. // Remove requests that are older than the time window
  29. requestLog[ipAddress] = requestLog[ipAddress]
  30. .Where(time => now - time <= timeWindow)
  31. .ToList();
  32.  
  33. return requestLog[ipAddress].Count > threshold;
  34. }
  35.  
  36. public void CleanupOldEntries()
  37. {
  38. var now = DateTime.UtcNow;
  39. var keysToRemove = new List<IPAddress>();
  40.  
  41. foreach (var entry in requestLog)
  42. {
  43. if (!entry.Value.Any(time => now - time <= timeWindow))
  44. {
  45. keysToRemove.Add(entry.Key);
  46. }
  47. }
  48.  
  49. foreach (var key in keysToRemove)
  50. {
  51. requestLog.Remove(key);
  52. }
  53. }
  54.  
  55. // Main method added to start the program
  56. public static void Main(string[] args)
  57. {
  58. Console.WriteLine("DDoS Detector started...");
  59.  
  60. // Create an instance of DDoSDetector
  61. var detector = new DDoSDetector();
  62.  
  63. // Test with a sample IP address
  64. var ip = IPAddress.Parse("192.168.1.1");
  65. var isAttack = detector.IsAttackDetected(ip);
  66. Console.WriteLine($"Is DDoS Attack Detected for {ip}: {isAttack}");
  67.  
  68. // Cleanup old entries
  69. detector.CleanupOldEntries();
  70. }
  71. }
  72.  
Success #stdin #stdout 0.05s 30896KB
stdin
Standard input is empty
stdout
DDoS Detector started...
Is DDoS Attack Detected for 192.168.1.1: False