PCAP and PCAPNG parsers
This crate contains several parsers for PCAP and PCAPNG files.
The code is available on Github
and is part of the Rusticata project.
Example: generic parsing
The following code shows how to parse a file either in PCAP or PCAPNG format.
# extern crate nom;
# extern crate pcap_parser;
use pcap_parser::*;
use nom::IResult;
use std::fs::File;
use std::io::Read;
# fn main() {
# let path = "/tmp/file.pcap";
let mut file = File::open(path).unwrap();
let mut buffer = Vec::new();
file.read_to_end(&mut buffer).unwrap();
let mut num_packets = 0;
match PcapCapture::from_file(&buffer) {
Ok(capture) => {
println!("Format: PCAP");
for _packet in capture.iter_packets() {
num_packets += 1;
}
return;
},
_ => ()
}
match PcapNGCapture::from_file(&buffer) {
Ok(capture) => {
println!("Format: PCAPNG");
for _packet in capture.iter_packets() {
}
println!("Num sections: {}", capture.sections.len());
for (snum,section) in capture.sections.iter().enumerate() {
println!("Section {}:", snum);
for (inum,interface) in section.interfaces.iter().enumerate() {
println!(" Interface {}:", inum);
println!(" Linktype: {:?}", interface.header.linktype);
for _packet in section.iter_packets() {
num_packets += 1;
}
}
}
},
_ => ()
}
# }
The above code requires the file to be entirely loaded into memory. Other functions
in this crate allows for writing streaming parsers.
See pcap-tools for examples.