Count the number of packets with pyshark
Asked Answered
F

4

5

In this code with pyshark

import pyshark
cap = pyshark.FileCapture(filename)
i = 0
for idx, packet in enumerate(cap):
    i += 1
print i
print len(cap._packets)

i and len(cap._packets) give two different results. Why is that?

Fils answered 19/11, 2014 at 19:56 Comment(0)
E
0

A look at the source code reveals that _packets is a list containing packets and is only used internally:

When iterating through a FileCapture object with keep_packets = True packets are getting added to this list.


To get access to all packets in a FileCapture object you should iterate over it just like you did:

for packet in cap:
    do_something(packet)

But to count the amount of packets just do this:

packet_amount = len(cap)

or use a counter like you did, but don't use _packets as it does not contain the complete packet list.

Everyday answered 19/11, 2014 at 20:40 Comment(1)
packet_amount = len(cap) is returning 0 in python 3.8 and 3.9Thiouracil
F
12

Don't know if it works in Python 2.7, but in Python 3.4 len(cap) returns 0. The FileCapture object is a generator, so what worked for me is len([packet for packet in cap])

Fungal answered 23/5, 2016 at 8:47 Comment(2)
Why i get ` raise RuntimeError('This event loop is already running') RuntimeError: This event loop is already running` when running len([packet for packet in cap])?Fulbert
I face same problem, it returns 0 in python 3.8 and 3.9 alsoThiouracil
D
8

i too, len(cap) is 0, i thinks the answer is fail. if you want know len(cap), please load packet before print it. use: cap.load_packets()

cap.load_packets()
packet_amount = len(cap)
print packet_amount
Domicile answered 9/7, 2018 at 15:15 Comment(0)
E
0

A look at the source code reveals that _packets is a list containing packets and is only used internally:

When iterating through a FileCapture object with keep_packets = True packets are getting added to this list.


To get access to all packets in a FileCapture object you should iterate over it just like you did:

for packet in cap:
    do_something(packet)

But to count the amount of packets just do this:

packet_amount = len(cap)

or use a counter like you did, but don't use _packets as it does not contain the complete packet list.

Everyday answered 19/11, 2014 at 20:40 Comment(1)
packet_amount = len(cap) is returning 0 in python 3.8 and 3.9Thiouracil
M
0

Just adding another way using callback function. Also little bit faster approach.

length = 0 
def count_callback(pkt):
    global length
    length = length + 1

cap.apply_on_packets(count_callback)

print(length)
Merciless answered 6/10, 2021 at 13:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.