環境
- Time 2022-11-20
- WSL-Ubuntu 22.04
- Rust 1.65.0
- pnet 0.31.0
前言
說明
參考:https://docs.rs/pnet_datalink/0.31.0/pnet_datalink/linux
目標
前面使用了 pnet 傳送了一個資料包,這裡傳送一個資料包,然後接收並顯示出來。
接收資料
use pnet_datalink::{linux, Channel};
fn main() {
let interfaces = linux::interfaces();
let dummy: Vec<_> = interfaces
.into_iter()
.filter(|e| e.name == "mydummy")
.collect();
let config = linux::Config::default();
let channel = linux::channel(&dummy[0], config);
let (mut _sender, mut reader) = match channel {
Ok(Channel::Ethernet(tx, rx)) => (tx, rx),
_ => panic!("Not a valid channel returned"),
};
let bytes = reader.next().unwrap();
dbg!(bytes);
let string = String::from_utf8_lossy(bytes);
println!("reader: {}", string)
}
傳送資料
use pnet_datalink::{linux, Channel};
fn main() {
let interfaces = linux::interfaces();
let dummy: Vec<_> = interfaces
.into_iter()
.filter(|e| e.name == "mydummy")
.collect();
let config = linux::Config::default();
let channel = linux::channel(&dummy[0], config);
let (mut sender, mut _reader) = match channel {
Ok(Channel::Ethernet(tx, rx)) => (tx, rx),
_ => panic!("Not a valid channel returned"),
};
let buffer = String::from("hello, jiangbo");
sender.send_to(buffer.as_bytes(), None).unwrap().unwrap();
}
tcpdump 的顯示
21:09:17.441710 20:6a:69:61:6e:67 (oui Unknown) > 68:65:6c:6c:6f:2c (oui Unknown), ethertype Unknown (0x626f), length 14:
可以看到確實傳送了一個資料包
reader 顯示
reader: hello, jiangbo
總結
透過 dummy 和 pnet,實現了兩個程式之間的資料交換。