std-method
UdpSocket::peek_from: inspect next datagram
Observe a datagram without consuming it. In this single-reader fixture the subsequent receive obtains the same bytes. With multiple readers another reader could consume the datagram. Expected stdout (not executed): true Common mistake: Expecting peek to remove the message from the queue.
Formal Syntax & Structure
rust syntaxrust
socket.peek_from(&mut buf) -> io::Result<(usize, SocketAddr)>Working Example
Example Snippetrust
fn main() { use std::{net::{Ipv4Addr, UdpSocket}, time::Duration}; let sender = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); let receiver = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); receiver.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); sender.set_write_timeout(Some(Duration::from_secs(2))).unwrap(); sender.send_to(b"abc", receiver.local_addr().unwrap()).unwrap(); let mut a = [0; 8]; let mut b = [0; 8]; let (n, p) = receiver.peek_from(&mut a).unwrap(); let (m, q) = receiver.recv_from(&mut b).unwrap(); println!("{}", n == m && p == q && a[..n] == b[..m]);}