Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Last active October 22, 2022 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lovasoa/f225b2a312ab8e607c5c211bbb13814f to your computer and use it in GitHub Desktop.
Save lovasoa/f225b2a312ab8e607c5c211bbb13814f to your computer and use it in GitHub Desktop.
Ethernet echo server with a fixed delay between request and response
// See https://www.reddit.com/r/rust/comments/yaqsqe/how_to_delay_lots_of_synchronous_actions/?sort=new
use pnet::datalink::{self};
use pnet::datalink::Channel::Ethernet;
use pnet::datalink::DataLinkSender;
use pnet::packet::ethernet::MutableEthernetPacket;
use std::sync::mpsc;
use std::time::Instant;
fn main() {
let interface = &datalink::interfaces()[0];
match datalink::channel(interface, Default::default()) {
Ok(Ethernet(tx, mut rx)) => {
println!("Listening on interface '{}'", interface.name);
let (sender, receiver) = mpsc::channel();
launch_processing_thread(tx, receiver);
loop {
match rx.next() {
Ok(packet) => sender.send((Instant::now(), packet.into())).unwrap(),
Err(e) => {
panic!("An error occurred while reading: {}", e);
}
}
}
}
Ok(_) => panic!("Unhandled channel type"),
Err(e) => panic!("An error occurred when creating the datalink channel: {}", e)
};
}
const DELAY: std::time::Duration = std::time::Duration::from_millis(500);
fn launch_processing_thread(
mut tx: Box<dyn DataLinkSender + 'static>,
packets: mpsc::Receiver<(Instant, Vec<u8>)>
) {
std::thread::spawn(move || {
for (instant, mut packet) in packets {
request_to_response(&mut packet);
std::thread::sleep(DELAY.saturating_sub(instant.elapsed()));
tx.send_to(&packet, None);
}
});
}
fn request_to_response(packet: &mut Vec<u8>) {
println!("{}", String::from_utf8_lossy(&packet));
let mut new_packet = MutableEthernetPacket::new(packet).unwrap();
let new_destination = new_packet.get_source();
new_packet.set_source(new_packet.get_destination());
new_packet.set_destination(new_destination);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment