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(); } // Add current request requestLog[ipAddress].Add(now); // Remove old requests outside time window requestLog[ipAddress] = requestLog[ipAddress] .Where(time => now - time <= timeWindow) .ToList(); // Check if the number of requests exceeds the threshold return requestLog[ipAddress].Count > threshold; } public void CleanupOldEntries() { var now = DateTime.UtcNow; var keysToRemove = new List(); foreach (var entry in requestLog) { // Remove keys that have no requests in the time window if (!entry.Value.Any(time => now - time <= timeWindow)) { keysToRemove.Add(entry.Key); } } // Remove the keys outside the time window foreach (var key in keysToRemove) { requestLog.Remove(key); } } // The Main method is the entry point for the program public static void Main(string[] args) { // Create an instance of the DDoSDetector var detector = new DDoSDetector(requestThreshold: 100, timeWindowSeconds: 60); // Example usage of the DDoSDetector IPAddress testIp = IPAddress.Parse("192.168.1.1"); // Simulate requests from the IP address for (int i = 0; i < 120; i++) // Simulate 120 requests { if (detector.IsAttackDetected(testIp)) { Console.WriteLine("DDoS attack detected from IP: " + testIp); break; // Exit the loop if an attack is detected } else { Console.WriteLine($"Request {i + 1} from {testIp} - No attack detected"); } } // Optionally, cleanup old entries (this would typically run periodically) detector.CleanupOldEntries(); } }