std-method
Connected UDP peer
Set a default peer for UDP and restrict normal receives to that peer. This is not a TCP connection handshake or proof of peer availability. Both endpoints in the fixture use numeric loopback addresses. Expected stdout (not executed): ping Common mistake: Assuming UDP connect verifies a remote service is listening.
Formal Syntax & Structure
rust syntaxrust
socket.connect(peer) -> io::Result<()>; socket.send(bytes); socket.recv(buf)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.connect(receiver.local_addr().unwrap()).unwrap(); receiver.connect(sender.local_addr().unwrap()).unwrap(); sender.send(b"ping").unwrap(); let mut b = [0; 16]; let n = receiver.recv(&mut b).unwrap(); println!("{}", std::str::from_utf8(&b[..n]).unwrap());}