I would like to calculate the payload size of the packets from a PCAP file using Scapy below is where I found a function that does this and works out all the payload size stats eg median/min/max etc.
How can I use this function on my PCAP file and do I need to do anything to my PCAP file before I process it using this function.
Can this be written simpler?
def calc_IP_payload_size_features(packet_list, filter_con):
global IP_len
global IP_len_list
global slice_length
IP_len_list = []
for i, (packet, dev_name) in enumerate(packet_list):
try:
IP_len.append(packet["IP"].len - packet["IP"].ihl)
except IndexError:
# IP_len.append(0)
pass
yield packet, dev_name
# print("IP_len", IP_len)
IP_len_list.append(IP_len)
IP_len = []
for i, (data) in enumerate(IP_len_list):
if len(data) == 0:
data.append(0)
data = data[:min(slice_length, len(data)-1)]
min_ip_len = min(data) # minimum IP packet size
max_ip_len = max(data) # maximum IP packet size
q1_ip_len = np.percentile(data, 25) # first quartile of IP packet size
median_ip_len = np.percentile(data, 50) # median of IP packet size
mean_ip_len = np.mean(data) # mean of IP packet size
q3_ip_len = np.percentile(data, 75) # third quartile of IP packet size
var_ip_len = np.var(data) # variance of IP packet size
iqr_ip_len = q3_ip_len - q1_ip_len # IQR of IP packet size
# print(i, "IP payload size features: ", min_ip_len, max_ip_len, q1_ip_len, median_ip_len, mean_ip_len, q3_ip_len, var_ip_len, iqr_ip_len)
feature_list[i].append(min_ip_len)
feature_list[i].append(max_ip_len)
feature_list[i].append(q1_ip_len)
feature_list[i].append(median_ip_len)
feature_list[i].append(mean_ip_len)
feature_list[i].append(q3_ip_len)
feature_list[i].append(var_ip_len)
feature_list[i].append(iqr_ip_len)
You can read pcap files with scapy like this:
pcap_contents = rdpcap("/path/to/foo.pcap")
source: https://scapy.readthedocs.io/en/latest/usage.html#reading-pcap-files
This will return a scapy.plist.PacketList
, which you can iterate over using standard Python techniques, for example a for
loop:
for packet in pcap_contents:
print(len(packet))
Your loop however seems to expect the packet_list
to contain tuples of (packet, dev_name)
:
for i, (packet, dev_name) in enumerate(packet_list):
My random sample pcap file certainly didn't produce this kind of data, so you probably need to match each packet with a dev_name
first, to produce a list of (packet, dev_name)
tuple
s. This can be done using standard Python methods, eg with for
loops, or, if you've got a list of dev_names
where the indices match, you could zip
the lists:
packets = [IP()/TCP(), IP()/UDP()]
dev_names = ['foo', 'bar']
packet_list = zip(packets, dev_names)
filter_con
doesn't appear to be used, so I can't comment on that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.