private void lvData_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e) { if (e.ItemIndex > core.BanItems.Count - 1) { return; } try { var item = core.BanItems.ElementAt(e.ItemIndex); e.Item = new ListViewItem(); BanItem banItem = item.Value; e.Item.ImageIndex = banItem.status; e.Item.Text = ""; e.Item.SubItems.Add(banItem.IP); e.Item.SubItems.Add(banItem.count.ToString()); e.Item.SubItems.Add(banItem.StartTime.ToString()); e.Item.SubItems.Add(banItem.lastActive.ToString()); e.Item.SubItems.Add(banItem.status == 1 ? banItem.BanTime.ToString() : ""); e.Item.SubItems.Add(banItem.lastPorts); } catch (Exception ex) { e.Item = new ListViewItem(); e.Item.Text = "-"; e.Item.SubItems.Add("-"); e.Item.SubItems.Add("-"); e.Item.SubItems.Add("-"); e.Item.SubItems.Add("-"); e.Item.SubItems.Add("-"); e.Item.SubItems.Add(ex.Message); } }
private string GetBanIPs() { StringBuilder sb = new StringBuilder("8.8.8.8"); foreach (var kv in BanItems) { BanItem item = kv.Value; if (IsWhiteIP(item.IP)) { continue; } if (item.count >= Gate) { if (item.status == 0) { item.BanTime = DateTime.Now; } item.status = 1; sb.Append("," + item.IP); } } return(sb.ToString()); }
private void ThreadRun() { while (true) { try { Thread.Sleep(50); bool needUpdateRule = false; var ip = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); foreach (var tcp in ip.GetActiveTcpConnections()) { if (tcp.LocalEndPoint.Port == Port) { BanItem item = null; bool ok = BanItems.TryGetValue(tcp.RemoteEndPoint.Address.ToString(), out item); if (!ok) { item = new BanItem(); item.IP = tcp.RemoteEndPoint.Address.ToString(); item.StartTime = DateTime.Now; item.status = IsWhiteIP(item.IP) ? 2 : 0; } item.lastActive = DateTime.Now; if (item.count >= Gate && !item.ports.ContainsKey((ushort)tcp.RemoteEndPoint.Port) && item.status == 0) { needUpdateRule = true; } item.ports[(ushort)tcp.RemoteEndPoint.Port] = 0; BanItems[tcp.RemoteEndPoint.Address.ToString()] = item; } } foreach (var x in BanItems.ToArray()) { BanItem banItem = x.Value; TimeSpan ts = DateTime.Now - banItem.BanTime; if (banItem.status == 1 && ts.TotalMinutes > BanDuration) { BanItems.Remove(x.Key); needUpdateRule = true; } // 如果超过10分钟,次数都很少,属于比较正常的连接请求,则在最后一次活跃连接10分钟后清理 TimeSpan ts2 = DateTime.Now - banItem.lastActive; if (banItem.status != 1 && ts2.TotalMinutes > CleanInterval) { BanItems.Remove(x.Key); LogI(RULE_NAME + " clean " + banItem.ToString()); } } if (needUpdateRule) { updateRules(); } } catch (Exception e) { LogE(RULE_NAME + " error occure: " + e.Message); } } }