Skip to main content

UdpSocket

Struct UdpSocket 

pub struct UdpSocket { /* private fields */ }
Available on crate feature net only.
Expand description

A UDP socket.

UDP is “connectionless”, unlike TCP. Meaning, regardless of what address you’ve bound to, a UdpSocket is free to communicate with many different remotes. There are basically two main ways to use UdpSocket:

  • one to many: bind and use send_to and recv_from to communicate with many different addresses
  • one to one: connect and associate with a single address, using send and recv to communicate only with that remote address

§Examples

Bind and connect a pair of sockets and send a packet:

use std::net::SocketAddr;

use compio_net::UdpSocket;

let first_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
let second_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();

// bind sockets
let mut socket = UdpSocket::bind(first_addr).await.unwrap();
let first_addr = socket.local_addr().unwrap();
let mut other_socket = UdpSocket::bind(second_addr).await.unwrap();
let second_addr = other_socket.local_addr().unwrap();

// connect sockets
socket.connect(second_addr).await.unwrap();
other_socket.connect(first_addr).await.unwrap();

let buf = Vec::with_capacity(12);

// write data
socket.send("Hello world!").await.unwrap();

// read data
let (n_bytes, buf) = other_socket.recv(buf).await.unwrap();

assert_eq!(n_bytes, buf.len());
assert_eq!(buf, b"Hello world!");

Send and receive packets without connecting:

use std::net::SocketAddr;

use compio_net::UdpSocket;
use socket2::SockAddr;

let first_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
let second_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();

// bind sockets
let mut socket = UdpSocket::bind(first_addr).await.unwrap();
let first_addr = socket.local_addr().unwrap();
let mut other_socket = UdpSocket::bind(second_addr).await.unwrap();
let second_addr = other_socket.local_addr().unwrap();

let buf = Vec::with_capacity(32);

// write data
socket.send_to("hello world", second_addr).await.unwrap();

// read data
let ((n_bytes, addr), buf) = other_socket.recv_from(buf).await.unwrap();

assert_eq!(addr, first_addr);
assert_eq!(n_bytes, buf.len());
assert_eq!(buf, b"hello world");

Implementations§

§

impl UdpSocket

pub async fn bind(addr: impl ToSocketAddrsAsync) -> Result<UdpSocket, Error>

Creates a new UDP socket and attempt to bind it to the addr provided.

pub async fn connect(&self, addr: impl ToSocketAddrsAsync) -> Result<(), Error>

Connects this UDP socket to a remote address, allowing the send and recv to be used to send data and also applies filters to only receive data from the specified address.

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.

pub fn from_std(socket: UdpSocket) -> Result<UdpSocket, Error>

Creates new UdpSocket from a std::net::UdpSocket.

pub fn close(self) -> impl Future<Output = Result<(), Error>>

Close the socket. If the returned future is dropped before polling, the socket won’t be closed.

See TcpStream::close for more details.

pub fn peer_addr(&self) -> Result<SocketAddr, Error>

Returns the socket address of the remote peer this socket was connected to.

§Examples
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};

use compio_net::UdpSocket;
use socket2::SockAddr;

let socket = UdpSocket::bind("127.0.0.1:34254")
    .await
    .expect("couldn't bind to address");
socket
    .connect("192.168.0.1:41203")
    .await
    .expect("couldn't connect to address");
assert_eq!(
    socket.peer_addr().unwrap(),
    SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 41203))
);

pub fn local_addr(&self) -> Result<SocketAddr, Error>

Returns the local address that this socket is bound to.

§Example
use std::net::SocketAddr;

use compio_net::UdpSocket;
use socket2::SockAddr;

let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
let sock = UdpSocket::bind(&addr).await.unwrap();
// the address the socket is bound to
let local_addr = sock.local_addr().unwrap();
assert_eq!(local_addr, addr);

pub async fn recv<T>(&self, buffer: T) -> BufResult<usize, T>
where T: IoBufMut,

Receives a packet of data from the socket into the buffer, returning the original buffer and quantity of data received.

pub async fn recv_vectored<T>(&self, buffer: T) -> BufResult<usize, T>

Receives a packet of data from the socket into the buffer, returning the original buffer and quantity of data received.

pub async fn recv_managed(&self, len: usize) -> Result<Option<BufferRef>, Error>

Read some bytes from this source and return a BufferRef.

If len == 0, will use buffer pool’s inner buffer size as the max len; if len > 0, min(len, inner buffer size) will be the read max len.

pub fn recv_multi( &self, len: usize, ) -> impl Stream<Item = Result<BufferRef, Error>>

Read some bytes from this source and return a stream of BufferRefs.

If len == 0, will use buffer pool’s inner buffer size as the max len of each buffer; if len > 0, min(len, inner buffer size) will be the read max len of each buffer.

pub async fn send<T>(&self, buffer: T) -> BufResult<usize, T>
where T: IoBuf,

Sends some data to the socket from the buffer, returning the original buffer and quantity of data sent.

pub async fn send_vectored<T>(&self, buffer: T) -> BufResult<usize, T>
where T: IoVectoredBuf,

Sends some data to the socket from the buffer, returning the original buffer and quantity of data sent.

pub async fn recv_from<T>(&self, buffer: T) -> BufResult<(usize, SocketAddr), T>
where T: IoBufMut,

Receives a single datagram message on the socket. On success, returns the number of bytes received and the origin.

pub async fn recv_from_vectored<T>( &self, buffer: T, ) -> BufResult<(usize, SocketAddr), T>

Receives a single datagram message on the socket. On success, returns the number of bytes received and the origin.

pub async fn recv_from_managed( &self, len: usize, ) -> Result<Option<(BufferRef, SocketAddr)>, Error>

Read some bytes from this source and the runtime’s buffer pool and return a BufferRef with the sender address.

If len == 0, will use buffer pool’s inner buffer size as the max len; if len > 0, min(len, inner buffer size) will be the read max len

pub fn recv_from_multi( &self, ) -> impl Stream<Item = Result<RecvFromMultiResult, Error>>

Read some bytes from this source and the runtime’s buffer pool and return a stream of RecvFromMultiResult.

pub async fn recv_msg<T, C>( &self, buffer: T, control: C, ) -> BufResult<(usize, usize, SocketAddr), (T, C)>
where T: IoBufMut, C: IoBufMut,

Receives a single datagram message and ancillary data on the socket. On success, returns the number of bytes received and the origin.

pub async fn recv_msg_vectored<T, C>( &self, buffer: T, control: C, ) -> BufResult<(usize, usize, SocketAddr), (T, C)>

Receives a single datagram message and ancillary data on the socket. On success, returns the number of bytes received and the origin.

pub async fn recv_msg_managed<C>( &self, len: usize, control: C, ) -> Result<Option<(BufferRef, C, SocketAddr)>, Error>
where C: IoBufMut,

Receives a single datagram message on the socket from the runtime’s buffer pool, together with ancillary data. The ancillary data buffer is provided by the caller.

If len == 0, will use buffer pool’s inner buffer size as the max len; if len > 0, min(len, inner buffer size) will be the read max len

pub fn recv_msg_multi( &self, control_len: usize, ) -> impl Stream<Item = Result<RecvMsgMultiResult, Error>>

Receives multiple single datagram messages and ancillary data on the socket from the runtime’s buffer pool.

pub async fn send_to<T>( &self, buffer: T, addr: impl ToSocketAddrsAsync, ) -> BufResult<usize, T>
where T: IoBuf,

Sends data on the socket to the given address. On success, returns the number of bytes sent.

pub async fn send_to_vectored<T>( &self, buffer: T, addr: impl ToSocketAddrsAsync, ) -> BufResult<usize, T>
where T: IoVectoredBuf,

Sends data on the socket to the given address. On success, returns the number of bytes sent.

pub async fn send_msg<T, C>( &self, buffer: T, control: C, addr: impl ToSocketAddrsAsync, ) -> BufResult<usize, (T, C)>
where T: IoBuf, C: IoBuf,

Sends data on the socket to the given address accompanied by ancillary data. On success, returns the number of bytes sent.

pub async fn send_msg_vectored<T, C>( &self, buffer: T, control: C, addr: impl ToSocketAddrsAsync, ) -> BufResult<usize, (T, C)>
where T: IoVectoredBuf, C: IoBuf,

Sends data on the socket to the given address accompanied by ancillary data. On success, returns the number of bytes sent.

pub async fn send_zerocopy<T>( &self, buf: T, ) -> BufResult<usize, impl Future<Output = T> + use<T>>
where T: IoBuf,

Sends data on the socket with zero copy.

Returns the result of send and a future that resolves to the original buffer when the send is complete.

pub async fn send_zerocopy_vectored<T>( &self, buf: T, ) -> BufResult<usize, impl Future<Output = T> + use<T>>
where T: IoVectoredBuf,

Sends vectored data on the socket with zero copy.

Returns the result of send and a future that resolves to the original buffer when the send is complete.

pub async fn send_to_zerocopy<A, T>( &self, buffer: T, addr: A, ) -> BufResult<usize, impl Future<Output = T> + use<A, T>>

Sends data on the socket to the given address with zero copy.

Returns the result of send and a future that resolves to the original buffer when the send is complete.

pub async fn send_to_zerocopy_vectored<A, T>( &self, buffer: T, addr: A, ) -> BufResult<usize, impl Future<Output = T> + use<A, T>>

Sends vectored data on the socket to the given address with zero copy.

Returns the result of send and a future that resolves to the original buffer when the send is complete.

pub async fn send_msg_zerocopy<A, T, C>( &self, buffer: T, control: C, addr: A, ) -> BufResult<usize, impl Future<Output = (T, C)> + use<A, T, C>>
where A: ToSocketAddrsAsync, T: IoBuf, C: IoBuf,

Sends data with control message on the socket to the given address with zero copy.

Returns the result of send and a future that resolves to the original buffer when the send is complete.

pub async fn send_msg_zerocopy_vectored<A, T, C>( &self, buffer: T, control: C, addr: A, ) -> BufResult<usize, impl Future<Output = (T, C)> + use<A, T, C>>

Sends vectored data with control message on the socket to the given address with zero copy.

Returns the result of send and a future that resolves to the original buffer when the send is complete.

pub fn broadcast(&self) -> Result<bool, Error>

Gets the value of the SO_BROADCAST option for this socket.

For more information about this option, see set_broadcast.

pub fn set_broadcast(&self, on: bool) -> Result<(), Error>

Sets the value of the SO_BROADCAST option for this socket.

When enabled, this socket is allowed to send packets to a broadcast address.

pub fn multicast_loop_v4(&self) -> Result<bool, Error>

Gets the value of the IP_MULTICAST_LOOP option for this socket.

For more information about this option, see set_multicast_loop_v4.

pub fn set_multicast_loop_v4(&self, on: bool) -> Result<(), Error>

Sets the value of the IP_MULTICAST_LOOP option for this socket.

If enabled, multicast packets will be looped back to the local socket.

§Note

This may not have any effect on IPv6 sockets.

pub fn multicast_ttl_v4(&self) -> Result<u32, Error>

Gets the value of the IP_MULTICAST_TTL option for this socket.

For more information about this option, see set_multicast_ttl_v4.

pub fn set_multicast_ttl_v4(&self, ttl: u32) -> Result<(), Error>

Sets the value of the IP_MULTICAST_TTL option for this socket.

Indicates the time-to-live value of outgoing multicast packets for this socket. The default value is 1 which means that multicast packets don’t leave the local network unless explicitly requested.

§Note

This may not have any effect on IPv6 sockets.

pub fn multicast_loop_v6(&self) -> Result<bool, Error>

Gets the value of the IPV6_MULTICAST_LOOP option for this socket.

For more information about this option, see set_multicast_loop_v6.

pub fn set_multicast_loop_v6(&self, on: bool) -> Result<(), Error>

Sets the value of the IPV6_MULTICAST_LOOP option for this socket.

Controls whether this socket sees the multicast packets it sends itself.

§Note

This may not have any effect on IPv4 sockets.

pub fn tclass_v6(&self) -> Result<u32, Error>

Available on Android or DragonFly BSD or FreeBSD or Fuchsia or Linux or macOS or NetBSD or OpenBSD or Cygwin only.

Gets the value of the IPV6_TCLASS option for this socket.

For more information about this option, see set_tclass_v6.

pub fn set_tclass_v6(&self, tclass: u32) -> Result<(), Error>

Available on Android or DragonFly BSD or FreeBSD or Fuchsia or Linux or macOS or NetBSD or OpenBSD or Cygwin only.

Sets the value for the IPV6_TCLASS option on this socket.

Specifies the traffic class field that is used in every packet sent from this socket.

§Note

This may not have any effect on IPv4 sockets.

pub fn ttl_v4(&self) -> Result<u32, Error>

Gets the value of the IP_TTL option for this socket.

For more information about this option, see set_ttl_v4.

pub fn set_ttl_v4(&self, ttl: u32) -> Result<(), Error>

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.

pub fn tos_v4(&self) -> Result<u32, Error>

Available on neither Fuchsia nor Redox OS nor Solaris nor illumos nor Haiku.

Gets the value of the IP_TOS option for this socket.

For more information about this option, see set_tos_v4.

pub fn set_tos_v4(&self, tos: u32) -> Result<(), Error>

Available on neither Fuchsia nor Redox OS nor Solaris nor illumos nor Haiku.

Sets the value for the IP_TOS option on this socket.

This value sets the type-of-service field that is used in every packet sent from this socket.

§Note
  • This may not have any effect on IPv6 sockets.

pub fn join_multicast_v4( &self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr, ) -> Result<(), Error>

Executes an operation of the IP_ADD_MEMBERSHIP type.

This function specifies a new multicast group for this socket to join. The address must be a valid multicast address, and interface is the address of the local interface with which the system should join the multicast group. If it’s equal to INADDR_ANY then an appropriate interface is chosen by the system.

pub fn join_multicast_v6( &self, multiaddr: &Ipv6Addr, interface: u32, ) -> Result<(), Error>

Executes an operation of the IPV6_ADD_MEMBERSHIP type.

This function specifies a new multicast group for this socket to join. The address must be a valid multicast address, and interface is the index of the interface to join/leave (or 0 to indicate any interface).

pub fn leave_multicast_v4( &self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr, ) -> Result<(), Error>

Executes an operation of the IP_DROP_MEMBERSHIP type.

For more information about this option, see join_multicast_v4.

pub fn leave_multicast_v6( &self, multiaddr: &Ipv6Addr, interface: u32, ) -> Result<(), Error>

Executes an operation of the IPV6_DROP_MEMBERSHIP type.

For more information about this option, see join_multicast_v6.

pub fn take_error(&self) -> Result<Option<Error>, Error>

Returns the value of the SO_ERROR option.

pub unsafe fn get_socket_option<T>( &self, level: i32, name: i32, ) -> Result<T, Error>
where T: Copy,

Gets a socket option.

§Safety

The caller must ensure T is the correct type for level and name.

pub unsafe fn set_socket_option<T>( &self, level: i32, name: i32, value: &T, ) -> Result<(), Error>
where T: Copy,

Sets a socket option.

§Safety

The caller must ensure T is the correct type for level and name.

Trait Implementations§

§

impl AsFd for UdpSocket

Available on Unix only.
§

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
§

impl AsRawFd for UdpSocket

§

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
§

impl Clone for UdpSocket

§

fn clone(&self) -> UdpSocket

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for UdpSocket

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl FromRawFd for UdpSocket

Available on Unix only.
§

unsafe fn from_raw_fd(fd: i32) -> UdpSocket

Constructs a new instance of Self from the given raw file descriptor. Read more
§

impl ToSharedFd<Socket> for UdpSocket

§

fn to_shared_fd(&self) -> SharedFd<Socket>

Return a cloned SharedFd.

Auto Trait Implementations§

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
§

impl<T> AsSource for T
where T: AsFd,

§

fn source(&self) -> BorrowedFd<'_>

Returns the borrowed file descriptor.
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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> Ungil for T
where T: Send,