I need to obtain the number of packets in a pcap file using python and scapy, in an efficent way.
I now use the following python code:
from scapy import *
pcap_file = "path/to/pcap/file.pcap"
count = 0
for packet in scapy.PcapReader(pcap_file):
count += 1
But with big pcap files (hundreds of MB) it is not an efficient solution. Is there another way to obtain packets number without iterating all over them?
You can't. The pcap file format consists only of a file header followed by all the packet payloads preceded by a packet record header. Neither the file header contains a count of all packets, nor a packet record header contains the index of the current packet.
And while the pcapng format is more flexible it does not seem to be possible to get the number of packets without iterating either.