- Notifications
You must be signed in to change notification settings - Fork 14.1k
Description
With a zero length buffer UdpSocket recv() behaves differently from recv_from().
(Only tested on MacOS M1 processor)
recv_from() returns the following error:
Err(Error { kind: InvalidInput, message: "invalid argument" })
recv() instantly returns with Ok(0), even though no UDP packet has been received
I would expect both to return Err(Error { kind: InvalidInput, message: "invalid argument" })
Importance
The api is different for similar functions, I believe they should behave the same way.
I encountered the bug when using
let mut buf=Vec::with_capacity(MTU);
Which could be an easy to overlook mistake.
Also recv() is returning even though no UDP packet has been received, in my case this led to a thread consuming 100% of a CPU.
Test case:
#[cfg(test)] mod tests { use std::net::{Ipv4Addr, UdpSocket}; use super::*; #[test] fn test_rx_from() { let mut buf = [0; 0]; let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); let res = socket.recv_from(&mut buf); println!("{res:?}"); assert!(res.is_err()); } #[test] fn test_rx() { let mut buf = [0; 0]; let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); let res = socket.recv(&mut buf); println!("{res:?}"); assert!(res.is_err()); } }Expected
I expected to see this happen:
I would expect both to return Err(Error { kind: InvalidInput, message: "invalid argument" })
I would not expect that recv instantly return an Ok(0) even though no UDP packet has been received.
Actual
Instead, this happened:
running 2 tests Err(Error { kind: InvalidInput, message: "invalid argument" }) Ok(0) thread 'tests::test_rx' (15944916) panicked at src/main.rs:24:9: assertion failed: res.is_err() note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace test tests::test_rx_from ... ok test tests::test_rx ... FAILED failures: failures: tests::test_rx test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Meta
rustc --version --verbose:
rustc 1.93.0-nightly (80d8f292d 2025-11-25) binary: rustc commit-hash: 80d8f292d82d735f83417221dd63b0dd2bbb8dd2 commit-date: 2025-11-25 host: aarch64-apple-darwin release: 1.93.0-nightly LLVM version: 21.1.5 OS uname -a
Darwin xxxxxx 25.0.0 Darwin Kernel Version 25.0.0: Mon Aug 25 21:17:45 PDT 2025; root:xnu-12377.1.9~3/RELEASE_ARM64_T8103 arm64