using System; using System.Collections.Generic; using System.Linq; using System.Net; public class DDoSDetector { private Dictionary> requestLog; private readonly int threshold; private readonly TimeSpan timeWindow; public DDoSDetector(int requestThreshold = 100, int timeWindowSeconds = 60) { requestLog = new Dictionary>(); threshold = requestThreshold; timeWindow = TimeSpan.FromSeconds(timeWindowSeconds); } public bool IsAttackDetected(IPAddress ipAddress) { var now = DateTime.UtcNow; if (!requestLog.ContainsKey(ipAddress)) { requestLog[ipAddress] = new List(); } requestLog[ipAddress].Add(now); // Remove requests that are older than the time window requestLog[ipAddress] = requestLog[ipAddress] .Where(time => now - time <= timeWindow) .ToList(); return requestLog[ipAddress].Count > threshold; } public void CleanupOldEntries() { var now = DateTime.UtcNow; var keysToRemove = new List(); foreach (var entry in requestLog) { if (!entry.Value.Any(time => now - time <= timeWindow)) { keysToRemove.Add(entry.Key); } } foreach (var key in keysToRemove) { requestLog.Remove(key); } } // Main method added to start the program public static void Main(string[] args) { Console.WriteLine("DDoS Detector started..."); // Create an instance of DDoSDetector var detector = new DDoSDetector(); // Test with a sample IP address var ip = IPAddress.Parse("192.168.1.1"); var isAttack = detector.IsAttackDetected(ip); Console.WriteLine($"Is DDoS Attack Detected for {ip}: {isAttack}"); // Cleanup old entries detector.CleanupOldEntries(); } }