std-type

UdpSocket: datagram endpoints

UDP transmits individual datagrams without TCP-style delivery or ordering guarantees. This example sends a single small datagram between isolated loopback sockets. A successful send does not prove remote delivery. Expected stdout (not executed): one true Common mistake: Assuming UDP retransmits lost packets or delivers them in order.

Formal Syntax & Structure

rust syntaxrust
UdpSocket::bind(address) -> io::Result<UdpSocket>

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"one", receiver.local_addr().unwrap()).unwrap();    let mut b = [0; 16];    let (n, src) = receiver.recv_from(&mut b).unwrap();    println!("{} {}", std::str::from_utf8(&b[..n]).unwrap(), src == sender.local_addr().unwrap());}
Rust Reference