How to put pcap Packets into a Vec<Packet>

Please help I am quite new in Rust.

I try this code:

use pcap::Device;
use pcap::Packet;

fn main() {
    let mut cap = Device::lookup().unwrap().open().unwrap();

    let mut packets : Vec<Packet> = Vec::new();

    while let Ok(packet) = {
        println!("received packet! {:?}", packet);

and get this error at compile time:

error[E0499]: cannot borrow `cap` as mutable more than once at a time
 --> src/
9 |     while let Ok(packet) = {
  |                            ^^^ mutable borrow starts here in previous iteration of loop

Please surround your code and error message in code blocks with three backticks like this:

// your code here

It makes it a lot easier for us to read your question.

If you take a look at the doc for the Packet type, it is defined like this:

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

This lifetime on this type means that it contains a reference into some other value. In your case, this is a reference into the cap variable, which is where the actual data is stored. Repeated calls to next will overwrite that buffer, so you can't keep several packets alive simultaneously.

You should either handle each packet fully before asking for the next packet, or copy the data into a different buffer.

thanks for the guidance

1 Like

thanks Alice, I understand it now. So I better have my own data type with its own buffer and header into which I can copy the values from Packet structure, because a Packet variable does not have its own buffer it only has a reference to another buffer in cap variable, which will be overwritten with the next "next()" call.

1 Like


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.