Extract packet header using pcap library


#1

In the pcap crate found at https://crates.io/crates/pcap/ there is a struct called Packet that is defined like this:

pub struct Packet<'a> {
    pub header: &'a PacketHeader,
    pub data: &'a [u8],
}

I am trying to extract information from the PacketHeader field such as the Age. I get an error when trying to access the PacketHeader field directly. Here is the code:

extern crate pcap;

use pcap::{Device,Capture};

fn main() {
    // get the default Device
    let main_device = Device::lookup().unwrap();
    let mut cap = Capture::from_device(main_device).unwrap()
        .promisc(true)
        .snaplen(5000)
        .open().unwrap();
    cap.filter("dst port 80").unwrap();

    {
        // get a packet from this capture
        let mut packet = cap.next();
        println!("got a packet! {:?}", packet);
        let header = packet.header;
        println!("got a header! {:?}", header);
    }

    // print some stats
    let stats = cap.stats().unwrap();
    println!("Received: {}, dropped: {}, if_dropped: {}", stats.received,
             stats.dropped, stats.if_dropped);

}

Here is the error message:

src/main.rs:18:22: 18:35 error: attempted access of field `header` on type `core::result::Result<pcap::Packet<'_>, pcap::Error>`, but no field with that name was found
src/main.rs:18         let header = packet.header;
                                    ^~~~~~~~~~~~~
error: aborting due to previous error

Thanks for any advice!


#2

Always read error messages carefully. In this case, you can’t access a header because the packet is not a Packet. It appears that cap.next() can fail, and therefore returns a Result type, which contains either a packet or an error.

How to handle Result is part of all basic Rust introductions, so I won’t repeat that here in long form, but the alternatives are .unwrap() if errors should abort the process, several more methods on Result, e.g. for substituting a default, and most general, pattern matching on the Ok and Err enum variants.


#3

Thanks! Using .unwrap() on cap.next() is working for now. I’ll eventually convert that to the pattern matching of Ok and Err enums once I better understand how to use them.