首页 > 解决方案 > 计算源 IP 向目标 IP 发送数据包的次数

问题描述

所以这是我的代码:

pkt = PcapReader(r'C:\Users\snoopgrapes\Desktop\evidence-packet-analysis.pcap')

srce = []
dstn = []

dict = {}
for p in pkt:
    if IP in p:
        src = p[IP].src
        dst = p[IP].dst
        srce.append(str(src))
        dstn.append(str(dst))

我想计算源 IP 向目标 IP 地址发送数据包的次数。我已经能够将这些对添加到单独的列表中。我也可以合并两个列表。我还能够将 IP 对添加到字典中。如何计算 SRC IP 发送到 DST IP 的次数并将结果存储在字典中?

例子:

{50: 192.168.1.10, 10.10.10.50, 35:172.16.10.1,172.16.255.254}

标签: pythonlistdictionary

解决方案


您明确要求将字典作为结果对象——使用 a 可能是有意义的,Counter因为您正在计数。即使您需要 a dict,计数器也可以简单地转换为 1。我在这篇文章的末尾附上了一个例子。

字典

但是,要使用字典显式执行此操作,您可以使用defaultdict带有 ( source, destination) 对的 a 作为键,并为每对增加存储的数字:

from collections import defaultdict

# ...

counts = defaultdict(int)
for packet in packets:
    if IP in packet:
        source = packet[IP].src
        destination = packet[IP].dst
        counts[(source, destination)] += 1

最小的工作示例:

from collections import defaultdict

class ObjectDict(dict):
    def __getattr__(self, key):
        if key in self:
            return self[key]

IP = "IP"

packets = [
{
   "IP": ObjectDict({
      "src": "192.168.1.1",
      "dst": "192.168.1.1",
   }),
},
{
   "IP": ObjectDict({
      "src": "192.168.1.1",
      "dst": "192.168.1.1",
   }),
},
{
   "IP": ObjectDict({
      "src": "192.168.1.2",
      "dst": "192.168.1.1",
   }),
},
{
   "IP": ObjectDict({
      "src": "192.168.1.1",
      "dst": "192.168.1.2",
   }),
},
]

counts = defaultdict(int)
for packet in packets:
    if IP in packet:
        source = packet[IP].src
        destination = packet[IP].dst
        counts[(source, destination)] += 1

print(dict(counts))

输出:

{('192.168.1.1', '192.168.1.1'): 2, ('192.168.1.2', '192.168.1.1'): 1, ('192.168.1.1', '192.168.1.2'): 1}

如果 usingdefaultdict不是一个选项,您只需将添加行替换为:

counts[(source, destination)] = counts.get((source, destination), 0) + 1

利用可用于的默认值dict.get()

柜台

要使用 a Counter,你可以这样做

# assume same setup as above

counter_generator = ((p[IP].src, p[IP].dst) for p in packets if IP in p)
counts = Counter(counter_generator)

print(counts)
print()
print(dict(counts))

输出:

Counter({('192.168.1.1', '192.168.1.1'): 2, ('192.168.1.2', '192.168.1.1'): 1, ('192.168.1.1', '192.168.1.2'): 1})

{('192.168.1.1', '192.168.1.1'): 2, ('192.168.1.2', '192.168.1.1'): 1, ('192.168.1.1', '192.168.1.2'): 1}

推荐阅读