smoltcp-rs / smoltcp

a smol tcp/ip stack
BSD Zero Clause License
3.73k stars 414 forks source link

Writing a UDP stress-tester #299

Closed Hirrolot closed 5 years ago

Hirrolot commented 5 years ago

I want to write a program that sends a lot of UDP packets to a specified address. My code now looks like this:

use smoltcp::socket::{UdpPacketMetadata, UdpSocket, UdpSocketBuffer};
use smoltcp::wire::IpEndpoint;

fn main() {
    let rx_buffer = UdpSocketBuffer::new(Vec::new(), Vec::new());
    let tx_buffer = UdpSocketBuffer::new(
        vec![UdpPacketMetadata::EMPTY; 1024 * 1024],
        vec![0; 1024 * 1024],
    );
    let mut socket = UdpSocket::new(rx_buffer, tx_buffer);
    let endpoint = "127.0.0.1:7256".parse::<IpEndpoint>().unwrap();
    socket.bind(endpoint).unwrap();

    let packet = vec![0; 5000];
    for i in 0..1000000 {
        socket.send_slice(&packet, endpoint).unwrap();
        dbg!(i);
    }
}

After 208 iterations I received this error:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Exhausted', src/libcore/result.rs:999:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

I already know that this is because I allocated too small receiving and transmission buffers, but if I allocate larger buffers, the program will just crash because my RAM is not infinite.

When I rewrite the code above using the standard UdpSocket, everything works fine but not so fast. How to solve this problem, or maybe I should read some articles or docs?

whitequark commented 5 years ago

I already know that this is because I allocated too small receiving and transmission buffers, but if I allocate larger buffers, the program will just crash because my RAM is not infinite.

That's not what's happening here. smoltcp is not a drop-in replacement for your OS' network stack, and in particular, it will never make any system calls directly. Since you are not polling the smoltcp UdpSocket, the data just sits there doing nothing.

For your use case, it sounds like you just want raw sockets and not a complete network stack.

Hirrolot commented 5 years ago

Thank you