pub struct UdpSocket { /* private fields */ }
Expand description
A UDP socket.
After creating a UdpSocket
by bind
ing it to a socket address, data can
be sent to and received from any other socket address.
Although UDP is a connectionless protocol, this implementation provides an
interface to set an address where data should be sent and received from.
After setting a remote address with connect
, data can be sent to and
received from that address with send
and recv
.
As stated in the User Datagram Protocol’s specification in IETF RFC 768,
UDP is an unordered, unreliable protocol; refer to TcpListener
and
TcpStream
for TCP primitives.
Examples
use lunatic::net::UdpSocket;
#[lunatic::main]
fn main(_: Mailbox<()>) -> std::io::Result<()> {
{
let socket = UdpSocket::bind("127.0.0.1:34254")?;
// Receives a single datagram message on the socket. If `buf` is too small to hold
// the message, it will be cut off.
let mut buf = [0; 10];
let (amt, src) = socket.recv_from(&mut buf)?;
// Redeclare `buf` as slice of the received data and send reverse data back to origin.
let buf = &mut buf[..amt];
buf.reverse();
socket.send_to(buf, &src)?;
} // the socket is closed here
Ok(())
}
Implementations§
source§impl UdpSocket
impl UdpSocket
sourcepub fn bind<A>(addr: A) -> Result<Self>where
A: ToSocketAddrs,
pub fn bind<A>(addr: A) -> Result<Self>where A: ToSocketAddrs,
Creates a new UdpSocket
bound to the given address.
Binding with a port number of 0 will request that the operating system assigns an available port to this listener.
If addr
yields multiple addresses, binding will be attempted with each
of the addresses until one succeeds and returns the listener. If
none of the addresses succeed in creating a listener, the error from
the last attempt is returned.
sourcepub fn local_addr(&self) -> Result<SocketAddr>
pub fn local_addr(&self) -> Result<SocketAddr>
Returns the local address that this UdpSocket is bound to.
This can be useful, for example, to identify when binding to port 0 which port was assigned by the OS.
sourcepub fn peer_addr(&self) -> Result<SocketAddr>
pub fn peer_addr(&self) -> Result<SocketAddr>
Returns the remote address this socket was connected to.
sourcepub fn connect<A>(&self, addr: A) -> Result<()>where
A: ToSocketAddrs,
pub fn connect<A>(&self, addr: A) -> Result<()>where A: ToSocketAddrs,
Connects this UDP socket to a remote address, allowing the send
and
recv
syscalls to be used to send data and also applies filters to only
receive data from the specified address.
If addr
yields multiple addresses, connect
will be attempted with
each of the addresses until the underlying OS function returns no
error. Note that usually, a successful connect
call does not specify
that there is a remote server listening on the port, rather, such an
error would only be detected after the first send. If the OS returns an
error for each of the specified addresses, the error returned from the
last connection attempt (the last address) is returned.
Examples
Creates a UDP socket bound to 127.0.0.1:3400
and connect the socket to
127.0.0.1:8080
:
use lunatic::net::UdpSocket;
let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
socket.connect("127.0.0.1:8080").expect("connect function failed");
Unlike in the TCP case, passing an array of addresses to the connect
function of a UDP socket is not a useful thing to do: The OS will be
unable to determine whether something is listening on the remote
address without the application sending data.
sourcepub fn send(&self, buf: &[u8]) -> Result<usize>
pub fn send(&self, buf: &[u8]) -> Result<usize>
Sends data on the socket to the remote address to which it is connected.
UdpSocket::connect
will connect this socket to a remote address.
This method will fail if the socket is not connected.
Examples
use lunatic::net::UdpSocket;
let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.connect("127.0.0.1:8080").expect("connect function failed");
socket.send(&[0, 1, 2]).expect("couldn't send message");
sourcepub fn send_to<A>(&self, buf: &[u8], addr: A) -> Result<usize>where
A: ToSocketAddrs,
pub fn send_to<A>(&self, buf: &[u8], addr: A) -> Result<usize>where A: ToSocketAddrs,
Sends data on the socket to the given address. On success, returns the number of bytes written.
Address type can be any implementor of super::ToSocketAddrs
trait.
See its documentation for concrete examples.
It is possible for addr
to yield multiple addresses, but send_to
will only send data to the first address yielded by addr
.
This will return an error when the IP version of the local socket
does not match that returned from super::ToSocketAddrs
.
Examples
use lunatic::net::UdpSocket;
let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.send_to(&[0; 10], "127.0.0.1:4242").expect("couldn't send data");
sourcepub fn recv(&self, buf: &mut [u8]) -> Result<usize>
pub fn recv(&self, buf: &mut [u8]) -> Result<usize>
Receives a single datagram message on the socket from the remote address to which it is connected. On success, returns the number of bytes read.
The function must be called with valid byte array buf
of sufficient
size to hold the message bytes. If a message is too long to fit in
the supplied buffer, excess bytes may be discarded.
UdpSocket::connect
will connect this socket to a remote address.
This method will fail if the socket is not connected.
Examples
use lunatic::net::UdpSocket;
let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.connect("127.0.0.1:8080").expect("connect function failed");
let mut buf = [0; 10];
match socket.recv(&mut buf) {
Ok(received) => println!("received {received} bytes {:?}", &buf[..received]),
Err(e) => println!("recv function failed: {e:?}"),
}
sourcepub fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>
pub fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>
Receives a single datagram message on the socket. On success, returns the number of bytes read and the origin.
The function must be called with valid byte array buf
of sufficient
size to hold the message bytes. If a message is too long to fit in
the supplied buffer, excess bytes may be discarded.
Examples
use lunatic::net::UdpSocket;
let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
let mut buf = [0; 10];
let (number_of_bytes, src_addr) = socket.recv_from(&mut buf)
.expect("Didn't receive data");
let filled_buf = &mut buf[..number_of_bytes];
sourcepub fn set_ttl(&self, ttl: u32) -> Result<()>
pub fn set_ttl(&self, ttl: u32) -> Result<()>
Sets the value for the IP_TTL
option on this socket.
This value sets the time-to-live field that is used in every packet sent from this socket.
Examples
use lunatic::net::UdpSocket;
let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_ttl(42).expect("set_ttl call failed");
sourcepub fn set_broadcast(&self, broadcast: bool) -> Result<()>
pub fn set_broadcast(&self, broadcast: bool) -> Result<()>
Sets the value of the SO_BROADCAST
option for this socket.
When enabled, this socket is allowed to send packets to a broadcast address.
Examples
use lunatic::net::UdpSocket;
let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_broadcast(false).expect("set_broadcast call failed");
sourcepub fn ttl(&self) -> Result<u32>
pub fn ttl(&self) -> Result<u32>
Gets the value of the IP_TTL
option for this socket.
For more information about this option, see UdpSocket::set_ttl
.
Examples
use lunatic::net::UdpSocket;
let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_ttl(42).expect("set_ttl call failed");
assert_eq!(socket.ttl().unwrap(), 42);
sourcepub fn broadcast(&self) -> Result<bool>
pub fn broadcast(&self) -> Result<bool>
Gets the value of the SO_BROADCAST
option for this socket.
For more information about this option, see
UdpSocket::set_broadcast
.
Examples
use lunatic::net::UdpSocket;
let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_broadcast(false).expect("set_broadcast call failed");
assert_eq!(socket.broadcast().unwrap(), false);
sourcepub fn try_clone(&self) -> Result<UdpSocket>
pub fn try_clone(&self) -> Result<UdpSocket>
Creates a new independently owned handle to the underlying socket.
The returned UdpSocket
is a reference to the same socket that this
object references. Both handles will read and write the same port, and
options set on one socket will be propagated to the other.
Examples
use lunatic::net::UdpSocket;
let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
let socket_clone = socket.try_clone().expect("couldn't clone the socket");
sourcepub fn set_nonblocking(&self, _: bool) -> Result<()>
pub fn set_nonblocking(&self, _: bool) -> Result<()>
Dummy fn - This is just to make porting from std easier?
sourcepub fn take_error(&self) -> Result<Option<LunaticError>>
pub fn take_error(&self) -> Result<Option<LunaticError>>
Dummy fn - This is just to make porting from std easier?