Struct std::net::UdpSocket
Re-export from std::net::unix::UdpSocket
A UDP socket
Example
This example sends a DNS query to CloudFlare's DNS server and prints the response metadata.
use std::net::{SocketAddr, UdpSocket};
use std::io::Result;
fn dns_query() -> Result<()> {
let request = std::concat!(
"\x00\x01", // Transaction id
"\x01\x20", // Flags (standard query)
"\x00\x01", // Question RRs
"\x00\x00", // Answer RRs
"\x00\x00", // Authority RRs
"\x00\x00", // Additional RRs
"\x04docs", // Domain name
"\x0calumina-lang",
"\x03net",
"\0",
"\x00\x1c", // Type (AAAA)
"\x00\x01" // Class (IN)
);
// Bind on a random local port
let local_addr = SocketAddr::parse("[::]:0").unwrap();
// Cloudflare DNS resolver
let remote_addr = SocketAddr::parse("[2606:4700:4700::1111]:53").unwrap();
let socket = UdpSocket::bind(&local_addr)?;
defer socket.close();
socket.send_to(request, &remote_addr)?;
let buf: [u8; 65536];
let (size, src) = socket.recv_from(&buf)?;
println!("Received {} bytes from {}", size, src);
println!(" {} questions", (&buf[4] as &u16).from_be());
println!(" {} answers", (&buf[6] as &u16).from_be());
println!(" {} authorities", (&buf[8] as &u16).from_be());
println!(" {} additional", (&buf[10] as &u16).from_be());
Result::ok(())
}
dns_query().unwrap();
Run this example
Fields
-
socket: Socket
Methods
impl UdpSocket { ... }
-
Create a new UDP socket from a raw socket.
-
fn bind(addr: &SocketAddr) -> Result<UdpSocket>
Creates a new UDP socket bound to the specified address.
-
fn connect(self: &UdpSocket, addr: &SocketAddr) -> Result<()>
-
fn recv_from(self: &UdpSocket, buf: &mut [u8]) -> Result<(usize, SocketAddr)>
Receives data from the socket.
Returns the number of bytes read and the address from which the data was received.
-
fn peek_from(self: &UdpSocket, buf: &mut [u8]) -> Result<(usize, SocketAddr)>
Receives data from the socket without consuming it.
Subsequent calls to recv will return the same data.
-
fn send_to(self: &UdpSocket, buf: &[u8], addr: &SocketAddr) -> Result<usize>
Sends data to a particular address.
-
Receives data from the socket.
-
Receives data from the socket without consuming it.
-
Sends data to the socket.
-
fn as_fd(self: &UdpSocket) -> FileDescriptor
-
fn peer_addr(self: &UdpSocket) -> Result<SocketAddr>
Returns the address of the remote peer
-
fn socket_addr(self: &UdpSocket) -> Result<SocketAddr>
Returns the address of the remote peer
-
Closes the socket.