Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the UDP server example safe?

I have a UDP server example, which is working:

let mut socket = UdpSocket::bind("127.0.0.1:12345")?;
let mut buf = [0; 4096];
loop {
    let sock = socket.try_clone()?;
    match socket.recv_from(&mut buf) {
        Ok((amt, src)) => {
            thread::spawn(move || {
                println!("Handling connection from {}", &src);
                let buf = &mut buf[..amt];
                buf.reverse();
                sock.send_to(&buf, &src).expect("error sending");
            });
        },
        Err(err) => {
            eprintln!("Err: {}", err);
        }
    }
}

It looks like all incoming UDP packets are sharing the same buffer.

If two UDP packets arrive at the same time, won't the second packet overwrite the first in buf, leading to the second packet's (reversed) content being sent back to both senders?

How does Rust prevent this?

like image 431
fadedbee Avatar asked Oct 23 '25 02:10

fadedbee


1 Answers

No, the buffer is not shared among threads but implicitly copied before starting a new one. From the array doc:

Arrays of any size are Copy if the element type is Copy

Therefore a move keyword forces a buffer movement, which leads to a copy since the same buffer can be used at the next iteration of the loop.

like image 106
Kitsu Avatar answered Oct 25 '25 00:10

Kitsu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!