compio_net

Struct UdpSocket

Source
pub struct UdpSocket { /* private fields */ }
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§

Source§

impl UdpSocket

Source

pub async fn bind(addr: impl ToSocketAddrsAsync) -> Result<Self>

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

Source

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

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.

Source

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

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

Source

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

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

Source

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

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))
);
Source

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

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);
Source

pub async fn recv<T: IoBufMut>(&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.

Source

pub async fn recv_vectored<T: IoVectoredBufMut>( &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.

Source

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

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

Source

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

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

Source

pub async fn recv_from<T: IoBufMut>( &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.

Source

pub async fn recv_from_vectored<T: IoVectoredBufMut>( &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.

Source

pub async fn recv_msg<T: IoBufMut, C: IoBufMut>( &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.

Source

pub async fn recv_msg_vectored<T: IoVectoredBufMut, C: IoBufMut>( &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.

Source

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

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

Source

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

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

Source

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

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

Source

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

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

Source

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

Gets a socket option.

§Safety

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

Source

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

Sets a socket option.

§Safety

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

Trait Implementations§

Source§

impl AsRawFd for UdpSocket

Source§

fn as_raw_fd(&self) -> RawFd

Extracts the raw file descriptor. Read more
Source§

impl Clone for UdpSocket

Source§

fn clone(&self) -> UdpSocket

Returns a copy of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for UdpSocket

Source§

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

Formats the value using the given formatter. Read more
Source§

impl FromRawFd for UdpSocket

Available on Unix only.
Source§

unsafe fn from_raw_fd(fd: RawFd) -> Self

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

impl ToSharedFd<Socket> for UdpSocket

Source§

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
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, dst: *mut u8)

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

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

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

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

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

impl<T> WithSubscriber for T

Source§

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

fn with_current_subscriber(self) -> WithDispatch<Self>

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