embassy-net

Crates

git

Versions

default

Flavors

Skip to main content

UdpSocket

Struct UdpSocket 

Source
pub struct UdpSocket<'d> { /* private fields */ }
Expand description

An UDP socket.

Implementations§

Source§

impl<'d> UdpSocket<'d>

Source

pub fn new(stack: Stack<'d>) -> Result<Self, Full>

Create a new UDP socket using the provided stack.

Errors:

  • Full if the stack has no room for another UDP socket. The limit is set by the udp-socket-count-N feature of xarxa.
Source

pub fn bind( &mut self, local: impl Into<ListenSocketAddr>, remote: impl Into<ListenSocketAddr>, ) -> Result<(), BindError>

Bind the socket.

This method opens the socket and configures which packets it will send and receive. It is equivalent to bind() and/or connect() in the BSD / Linux socket API.

§Local address
  • None: the socket sends/receives packets with any local address. It receives packets destined to unicast, multicast and broadcast addresses.
  • Some(V4(UNSPECIFIED)): same as None, but IPv4 packets only.
  • Some(V6(UNSPECIFIED)): same as None, but IPv6 packets only.
  • Some(_): the socket sends/receives packets from/to the given local address only.
    • If unicast, the stack checks the address is ours, else returns Unaddressable.
    • Multicast and broadcast addresses are allowed, but then the socket can receive only, not send.
§Local port
  • 0: the stack allocates an unused ephemeral port. You can retrieve it with local_addr.
  • non-zero: the given port is used.

The socket only receives packets to that port and sends from that port. A UDP socket must be bound to at least a port, there’s no way to make a UDP socket listen on all ports.

§Remote address
  • None: the socket sends/receives packets with any remote address.
  • Some(V4(UNSPECIFIED)): same as None, but IPv4 packets only.
  • Some(V6(UNSPECIFIED)): same as None, but IPv6 packets only.
  • Some(_): the socket sends/receives packets to/from the given remote address only. Multicast and broadcast addresses are allowed, but then the socket can send only, not receive.
§Remote port
  • 0: the socket sends/receives packets to/from any remote port.
  • non-zero: the socket sends/receives packets to/from the given port only.

Overlapping bindings between sockets are allowed as long as they’re not identical. For example you can bind a socket to *:53 and another to 1.2.3.4:53, but you can’t bind two sockets to *:53. If a packet matches multiple sockets, the one with the most specific binding wins. Packets are not duplicated, only the winning socket will receive it.

Multicast groups are not joined automatically, you must call Iface::join_multicast_group yourself.

§Errors
  • InvalidState: if the socket is already bound (see is_open).
  • InUse: on an identical bind.
  • NoFreePorts: if the ephemeral range is exhausted.
  • Unaddressable: on an address family mismatch, if the local address is not ours, or if no local address is available for the given remote.
Source

pub fn bind_to_iface( &mut self, iface: Option<IfaceHandle>, ) -> Result<(), BindError>

Bind the socket to an interface, or unbind it with None.

A socket bound to an interface only sends and receives packets on it:

  • Destinations must be on-link on that iface, or have a route through it.
  • Broadcast and multicast destinations go out on that iface only
  • Local addresses will be picked from that iface only.

The socket must be closed. The binding is kept across close, so a socket stays bound to its interface when it is bound again.

Two sockets with otherwise identical tuples may coexist if they are bound to different interfaces. On ingress, a socket bound to the arrival interface wins over an unbound one with an equal tuple.

§Errors
  • InvalidState: if the socket is open.
Source

pub fn bound_iface(&self) -> Option<IfaceHandle>

Return the interface the socket is bound to, or None.

See bind_to_iface.

Source

pub fn wait_recv_ready(&self) -> impl Future<Output = ()> + '_

Wait until the socket becomes readable.

A socket is readable when a packet has been received, or when there are queued packets in the buffer.

Source

pub fn poll_recv_ready(&self, cx: &mut Context<'_>) -> Poll<()>

Wait until a datagram can be read.

When no datagram is readable, this method will return Poll::Pending and register the current task to be notified when a datagram is received.

When a datagram is received, this method will return Poll::Ready.

Source

pub fn recv_from<'s>( &'s self, buf: &'s mut [u8], ) -> impl Future<Output = Result<(usize, UdpMetadata), RecvError>> + 's

Dequeue a received datagram, copying the payload into the given slice, and return the number of octets copied along with its metadata.

This method will wait until a datagram is received.

See also recv.

§Errors
  • InvalidState: if the socket is not bound.
  • Truncated: if buf is smaller than the payload. The packet is dropped.
  • IcmpError: with the icmp-errors feature, if an ICMP error is pending. See recv.
Source

pub fn try_recv_from( &self, buf: &mut [u8], ) -> Result<(usize, UdpMetadata), TryError<RecvError>>

Dequeue a received datagram, copying the payload into the given slice, and return the number of octets copied along with its metadata.

This method will not wait for a datagram to be received.

See also try_recv.

§Errors
  • WouldBlock: if no datagram is available.
  • Other(InvalidState): if the socket is not bound.
  • Other(Truncated): if buf is smaller than the payload. The packet is dropped.
  • Other(IcmpError): with the icmp-errors feature, if an ICMP error is pending. See recv.
Source

pub fn poll_recv_from( &self, buf: &mut [u8], cx: &mut Context<'_>, ) -> Poll<Result<(usize, UdpMetadata), RecvError>>

Dequeue a received datagram, copying the payload into the given slice, and return the number of octets copied along with its metadata.

When no datagram is available, this method will return Poll::Pending and register the current task to be notified when a datagram is received.

When a datagram is received, this method will return Poll::Ready with the number of bytes received and the remote address.

See also recv.

§Errors
  • InvalidState: if the socket is not bound.
  • Truncated: if buf is smaller than the payload. The packet is dropped.
  • IcmpError: with the icmp-errors feature, if an ICMP error is pending. See recv.
Source

pub async fn recv(&self) -> Result<RecvPacket, RecvError>

Dequeue a received datagram, as an owned packet (RecvPacket).

This is zero-copy: the returned value is the buffer the datagram arrived in.

This method will wait until a datagram is received.

§Errors
  • InvalidState: if the socket is not bound.
  • IcmpError: with the icmp-errors feature, if an ICMP error is pending. It is reported before any queued datagram, once, and taking it clears it.
Source

pub fn try_recv(&self) -> Result<RecvPacket, TryError<RecvError>>

Dequeue a received datagram, as an owned packet (RecvPacket).

This is zero-copy: the returned value is the buffer the datagram arrived in.

This method will not wait for a datagram to be received.

§Errors
  • WouldBlock: if no datagram is available.
  • Other(InvalidState): if the socket is not bound.
  • Other(IcmpError): with the icmp-errors feature, if an ICMP error is pending. It is reported before any queued datagram, once, and taking it clears it.
Source

pub async fn recv_from_with<R>( &mut self, f: impl FnOnce(&[u8], UdpMetadata) -> R, ) -> Result<R, RecvError>

Receive a datagram with a zero-copy function.

When no datagram is available, this method will return Poll::Pending and register the current task to be notified when a datagram is received.

When a datagram is received, this method will call the provided function with a reference to the received bytes and the remote address and return Poll::Ready with the function’s returned value.

Source

pub fn try_recv_from_with<R>( &mut self, f: impl FnOnce(&[u8], UdpMetadata) -> R, ) -> Result<R, TryError<RecvError>>

Receive a datagram with a zero-copy function.

This method will not wait for a datagram to be received.

If no datagram is available, this method will return Err(TryError::WouldBlock).

Source

pub fn peek_from<'s>( &'s self, buf: &'s mut [u8], ) -> impl Future<Output = Result<(usize, UdpMetadata), RecvError>> + 's

Peek at the next received datagram without dequeueing it, copying the payload into the given slice.

This method will wait until a datagram is received.

§Errors
  • InvalidState: if the socket is not bound.
  • Truncated: if buf is smaller than the payload. No data is copied and the packet stays in the queue.
Source

pub fn try_peek_from( &self, buf: &mut [u8], ) -> Result<(usize, UdpMetadata), TryError<RecvError>>

Peek at the next received datagram without dequeueing it, copying the payload into the given slice.

This method will not wait for a datagram to be received.

§Errors
  • WouldBlock: if no datagram is available.
  • Other(InvalidState): if the socket is not bound.
  • Other(Truncated): if buf is smaller than the payload. No data is copied and the packet stays in the queue.
Source

pub fn poll_peek_from( &self, buf: &mut [u8], cx: &mut Context<'_>, ) -> Poll<Result<(usize, UdpMetadata), RecvError>>

Peek at the next received datagram without dequeueing it, copying the payload into the given slice.

When no datagram is available, this method will return Poll::Pending and register the current task to be notified when a datagram is received.

§Errors
  • InvalidState: if the socket is not bound.
  • Truncated: if buf is smaller than the payload. No data is copied and the packet stays in the queue.
Source

pub async fn peek_from_with<R>( &self, f: impl FnOnce(&[u8], UdpMetadata) -> R, ) -> Result<R, RecvError>

Peek at the next received datagram without dequeueing it, calling f with its payload and its metadata.

This method will wait until a datagram is received.

§Errors
  • InvalidState: if the socket is not bound.
Source

pub fn try_peek_from_with<R>( &self, f: impl FnOnce(&[u8], UdpMetadata) -> R, ) -> Result<R, TryError<RecvError>>

Peek at the next received datagram without dequeueing it, calling f with its payload and its metadata.

This method will not wait for a datagram to be received.

§Errors
  • WouldBlock: if no datagram is available.
  • Other(InvalidState): if the socket is not bound.
Source

pub fn wait_send_ready(&self) -> impl Future<Output = ()> + '_

Wait until the socket becomes writable.

A socket becomes writable when the stack has a free packet buffer and the network device has room for a frame.

Source

pub fn poll_send_ready(&self, cx: &mut Context<'_>) -> Poll<()>

Wait until a datagram can be sent.

When no datagram can be sent (the stack has no free packet buffer, or the network device has no room), this method will return Poll::Pending and register the current task to be notified when it can.

When a datagram can be sent, this method will return Poll::Ready.

Source

pub async fn send_to( &self, buf: &[u8], remote: impl Into<UdpMetadata>, ) -> Result<(), SendError>

Send a datagram to the given remote address, copying the payload from a slice.

This method will wait until the datagram has been sent.

See send_to_with.

§Errors
  • InvalidState: if the socket is not bound.
  • Unaddressable: if the destination address or port is still unspecified after defaulting, the destination’s address family does not match the source address, no source address is available, or the source address is not assigned to any interface.
  • BufferFull: if the payload cannot fit in a packet buffer.
Source

pub fn try_send_to( &self, buf: &[u8], remote: impl Into<UdpMetadata>, ) -> Result<(), TryError<SendError>>

Send a datagram to the given remote address, copying the payload from a slice.

This method will not wait for a packet buffer or device room to become free.

See send_to_with.

§Errors
  • WouldBlock: if every packet buffer is in use, or the interface the datagram would go out of has no room for it right now.
  • Other(InvalidState): if the socket is not bound.
  • Other(Unaddressable): if the destination address or port is still unspecified after defaulting, the destination’s address family does not match the source address, no source address is available, or the source address is not assigned to any interface.
  • Other(BufferFull): if the payload cannot fit in a packet buffer.
Source

pub fn poll_send_to( &self, buf: &[u8], remote: impl Into<UdpMetadata>, cx: &mut Context<'_>, ) -> Poll<Result<(), SendError>>

Send a datagram to the given remote address, copying the payload from a slice.

When the datagram has been sent, this method will return Poll::Ready(Ok()).

When the datagram cannot be sent right now, this method will return Poll::Pending and register the current task to be notified when it can.

See send_to_with.

§Errors
  • InvalidState: if the socket is not bound.
  • Unaddressable: if the destination address or port is still unspecified after defaulting, the destination’s address family does not match the source address, no source address is available, or the source address is not assigned to any interface.
  • BufferFull: if the payload cannot fit in a packet buffer.
Source

pub async fn send_to_with<R>( &mut self, max_size: usize, remote: impl Into<UdpMetadata> + Copy, f: impl FnOnce(&mut [u8]) -> (usize, R), ) -> Result<R, SendError>

Send a datagram, building the payload in place.

The destination is remote.remote_addr, with unspecified parts defaulted from the socket’s bound remote address. On a connected socket, sending to SocketAddr::UNSPECIFIED sends to the connected remote. An explicitly specified destination is honored even on a connected socket.

The closure gets a max_size-byte slice inside a freshly allocated packet buffer, and returns how many bytes it wrote, along with a value that this method returns. The datagram is then sent immediately. If the destination’s neighbor is unresolved, the packet is queued inside the stack and sent when resolution completes. This still counts as a successful send.

This method will wait until a packet buffer is available before passing it to the closure.

remote.meta is attached to the packet and handed to the driver with it: an id to tag the packet with, or a request to timestamp its transmission (see Stack::poll_tx_timestamp).

§Errors
  • InvalidState: if the socket is not bound.
  • Unaddressable: if the destination address or port is still unspecified after defaulting, the destination’s address family does not match the source address, no source address is available, or the source address is not assigned to any interface.
  • BufferFull: if the payload cannot fit in a packet buffer.
Source

pub fn try_send_to_with<R>( &mut self, size: usize, remote: impl Into<UdpMetadata>, f: impl FnOnce(&mut [u8]) -> R, ) -> Result<R, TryError<SendError>>

Send a datagram, building the payload in place.

The destination is remote.remote_addr, with unspecified parts defaulted from the socket’s bound remote address. On a connected socket, sending to SocketAddr::UNSPECIFIED sends to the connected remote. An explicitly specified destination is honored even on a connected socket.

The closure gets a size-byte slice inside a freshly allocated packet buffer, fills it, and returns a value that this method returns. The datagram is then sent immediately. If the destination’s neighbor is unresolved, the packet is queued inside the stack and sent when resolution completes. This still counts as a successful send.

This method will not wait for a packet buffer to become free.

remote.meta is attached to the packet and handed to the driver with it: an id to tag the packet with, or a request to timestamp its transmission (see Stack::poll_tx_timestamp).

§Errors
  • WouldBlock: if every packet buffer is in use, or the interface the datagram would go out of has no room for it right now.
  • Other(InvalidState): if the socket is not bound.
  • Other(Unaddressable): if the destination address or port is still unspecified after defaulting, the destination’s address family does not match the source address, no source address is available, or the source address is not assigned to any interface.
  • Other(BufferFull): if the payload cannot fit in a packet buffer.
Source

pub fn local_addr(&self) -> ListenSocketAddr

Return the bound local address.

See bind for details on how UDP socket binding works.

Returns ListenSocketAddr::UNSPECIFIED if not bound.

Source

pub fn remote_addr(&self) -> ListenSocketAddr

Return the bound remote address.

See bind for details on how UDP socket binding works.

Returns ListenSocketAddr::UNSPECIFIED if not bound.

Source

pub fn is_open(&self) -> bool

Check whether the socket is open (bound to a port).

Source

pub fn close(&mut self)

Close the socket, unbinding it and dropping any queued packets.

Source

pub fn may_send(&self) -> bool

Returns whether the socket is ready to send data, i.e. it is bound and a packet buffer is free.

Source

pub fn may_recv(&self) -> bool

Returns whether the socket is ready to receive data, i.e. it has received a packet that’s now in the queue.

Source

pub fn can_recv(&self) -> bool

Check whether the RX queue is not empty.

Source

pub fn hop_limit(&self) -> Option<u8>

Return the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.

See also the set_hop_limit method.

Source

pub fn set_hop_limit( &mut self, hop_limit: Option<u8>, ) -> Result<(), InvalidHopLimit>

Set the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.

A socket without an explicitly set hop limit value uses the default IANA recommended value (64).

§Errors
  • InvalidHopLimit: if the hop limit is Some(0). A host must not send a packet with a hop limit of zero (RFC 1122 § 3.2.1.7). The socket is left unchanged.

Trait Implementations§

Source§

impl Drop for UdpSocket<'_>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

§

impl<'d> !RefUnwindSafe for UdpSocket<'d>

§

impl<'d> !Send for UdpSocket<'d>

§

impl<'d> !Sync for UdpSocket<'d>

§

impl<'d> !UnwindSafe for UdpSocket<'d>

§

impl<'d> Freeze for UdpSocket<'d>

§

impl<'d> Unpin for UdpSocket<'d>

§

impl<'d> UnsafeUnpin for UdpSocket<'d>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.