using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
public class DDoSDetector
{
private Dictionary<IPAddress, List<DateTime>> requestLog;
private readonly int threshold;
private readonly TimeSpan timeWindow;
public DDoSDetector(int requestThreshold = 100, int timeWindowSeconds = 60)
{
requestLog = new Dictionary<IPAddress, List<DateTime>>();
threshold = requestThreshold;
timeWindow = TimeSpan.FromSeconds(timeWindowSeconds);
}
public bool IsAttackDetected(IPAddress ipAddress)
{
var now = DateTime.UtcNow;
if (!requestLog.ContainsKey(ipAddress))
{
requestLog[ipAddress] = new List<DateTime>();
}
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<IPAddress>();
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("10.30.2.24");
var isAttack = detector.IsAttackDetected(ip);
Console.WriteLine($"Is DDoS Attack Detected for {ip}: {isAttack}");
// Cleanup old entries
detector.CleanupOldEntries();
}
}