0

我有一个 C# 程序,可以检测任何给定以太网设备上的传入 TCP/IP 数据包。每个数据包都在以下结构中处理:

struct Packet{
   String sourceIp;
   DateTime arrivalDate;
}

如果我有每个传入数据包的列表(列表),我如何在不到 Y 秒(比如 1 秒)内获得超过 X 个数据包的那些 IP?

我不知道如何解决这个问题,任何帮助/提示将不胜感激。

4

1 回答 1

1

使用 Linq,它将是这样的:

  List<Packet> allPackets =
     new List<Packet>
        {
           new Packet {arrivalDate = DateTime.Parse("2000-01-01 0:00:00"), sourceIp = "a"},
           new Packet {arrivalDate = DateTime.Parse("2000-01-01 0:00:01"), sourceIp = "a"},
           new Packet {arrivalDate = DateTime.Parse("2000-01-01 0:00:01"), sourceIp = "a"},
           new Packet {arrivalDate = DateTime.Parse("2000-01-01 0:01:00"), sourceIp = "a"},
           new Packet {arrivalDate = DateTime.Parse("2000-01-01 0:00:00"), sourceIp = "b"},
           new Packet {arrivalDate = DateTime.Parse("2000-01-01 0:01:00"), sourceIp = "b"},
           new Packet {arrivalDate = DateTime.Parse("2000-01-01 0:02:00"), sourceIp = "b"},
           new Packet {arrivalDate = DateTime.Parse("2000-01-01 0:03:00"), sourceIp = "b"},
        };
  var xPackets = 2;
  var interval = TimeSpan.FromSeconds(15);

  // We group all the packets by ip, then within that, order the packets by date.
  var ips =
     allPackets
        .GroupBy(
           p => p.sourceIp,
           (ip, packets) => new
                                {
                                   ip,
                                   packets = packets.OrderBy(p => p.arrivalDate).ToList()
                                })
        .ToList();
  // Build a list of IPs with at least x packets in y interval.
  var rapidIps = new List<string>();
  foreach (var ipPacket in ips)
  {
     for (int i = 0, j = xPackets; j < ipPacket.packets.Count; i++, j++)
     {
        if (ipPacket.packets[i].arrivalDate + interval >= ipPacket.packets[j].arrivalDate)
        {
           rapidIps.Add((ipPacket.ip));
           break;
        }

     }
  }

最后,rapidIps包含[a].

于 2012-05-26T22:04:25.493 回答