Created
April 12, 2011 09:52
-
-
Save remcoros/915266 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class IPFilter | |
{ | |
public static int MaxRequestsPerGarbageCollect = 60; | |
public static int GarbageCollectFrequencyInMinutes = 60; | |
public static Action<Entry> RequestExceededAction = (e) => { } | |
private static IDictionary<string, Entry> entries = new Dictionary<string, Entry>(); | |
private static DateTime lastGarbageCollect; | |
public static void Log(string ip) | |
{ | |
var entry = GetOrCreateEntry(ip); | |
entry.Requests++; | |
entry.LastRequest = DateTime.Now; | |
CheckEntry(entry); | |
GarbageCollect(); | |
} | |
private static Entry GetOrCreateEntry(string ip) | |
{ | |
Entry entry = null; | |
entries.TryGet(ip, out entry); | |
if (entry == null) | |
entry = new Entry() { Ip = ip }; | |
return entry; | |
} | |
private static void CheckEntry(Entry entry) | |
{ | |
if (entry.Requests > MaxRequestsPerGarbageCollect) | |
{ | |
RequestExceededAction(entry); | |
entries.Remove(entry.Ip); | |
} | |
} | |
private static void GarbageCollect() | |
{ | |
if (DateTime.Now <= lastGarbageCollect.AddMinutes(GarbageCollectFrequencyInMinutes)) | |
{ | |
return; | |
} | |
var oldEntries = entries.Where(kv=>kv.Value.LastRequest.AddMinutes(GarbageCollectFrequencyInMinutes) < DateTime.Now); | |
foreach(var kv in oldEntries) | |
{ | |
entries.Remove(kv); | |
} | |
} | |
public class Entry | |
{ | |
public string Ip { get; set; } | |
public int Requests { get; set; } | |
public DateTime LastRequest { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment