Skip to main content

UdpSocket

Struct UdpSocket 

Source
pub struct UdpSocket { /* private fields */ }
Expand description

An Udp Socket.

Implementations§

Source§

impl UdpSocket

Source

pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UdpSocket, ()>

Creates a UDP socket bound to the specified address.

Binding with port number 0 will request an available port from the OS.

This sets the ReusePort option on the socket, so if the OS-provided load balancing is enough, it is possible to just bind to the same address from multiple executors.

§Examples
use glommio::{net::UdpSocket, LocalExecutor};

let ex = LocalExecutor::default();
ex.run(async move {
    let listener = UdpSocket::bind("127.0.0.1:8000").unwrap();
    println!("Listening on {}", listener.local_addr().unwrap());
});
Source

pub async fn connect<A: ToSocketAddrs>(&self, addr: A) -> Result<(), ()>

Connects this UDP socket to a remote address, allowing the send and recv methods 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
use glommio::{net::UdpSocket, LocalExecutor};

let ex = LocalExecutor::default();
ex.run(async move {
    let receiver = UdpSocket::bind("127.0.0.1:0").unwrap();
    let sender = UdpSocket::bind("127.0.0.1:0").unwrap();
    receiver
        .connect(sender.local_addr().unwrap())
        .await
        .unwrap();
    sender
        .connect(receiver.local_addr().unwrap())
        .await
        .unwrap();
});
Source

pub fn set_buffer_size(&mut self, buffer_size: usize)

Sets the buffer size used on the receive path

Source

pub fn buffer_size(&mut self) -> usize

gets the buffer size used

Source

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
let s = UdpSocket::bind("127.0.0.1:10000").unwrap();
s.set_broadcast(false).expect("set_broadcast call failed");
assert_eq!(s.broadcast().unwrap(), false);
Source

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
let s = UdpSocket::bind("127.0.0.1:10000").unwrap();
s.set_broadcast(false).expect("set_broadcast call failed");
Source

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

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.

Source

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

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

Source

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

Executes an operation of the IP_DROP_MEMBERSHIP type.

For more information about this option, see UdpSocket::join_multicast_v4.

Source

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

Executes an operation of the IPV6_DROP_MEMBERSHIP type.

For more information about this option, see UdpSocket::join_multicast_v6.

Source

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

Gets the value of the IP_MULTICAST_LOOP option for this socket.

For more information about this option, see UdpSocket::set_multicast_loop_v4.

§Examples
let s = UdpSocket::bind("127.0.0.1:10000").unwrap();
s.set_multicast_loop_v4(false)
    .expect("set_multicast_loop_v4 call failed");
assert_eq!(s.multicast_loop_v4().unwrap(), false);
Source

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

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 that this may not have any effect on IPv6 sockets.

§Examples
let s = UdpSocket::bind("127.0.0.1:10000").unwrap();
s.set_multicast_loop_v4(false)
    .expect("set_multicast_loop_v4 call failed");
Source

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

Gets the value of the IPV6_MULTICAST_LOOP option for this socket.

For more information about this option, see UdpSocket::set_multicast_loop_v6.

§Examples
let s = UdpSocket::bind("127.0.0.1:10000").unwrap();
s.set_multicast_loop_v6(false)
    .expect("set_multicast_loop_v6 call failed");
assert_eq!(s.multicast_loop_v6().unwrap(), false);
Source

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

Sets the value of the IPV6_MULTICAST_LOOP option for this socket.

Controls whether this socket sees the multicast packets it sends itself. Note that this may not have any affect on IPv4 sockets.

§Examples
let s = UdpSocket::bind("127.0.0.1:10000").unwrap();
s.set_multicast_loop_v6(false)
    .expect("set_multicast_loop_v6 call failed");
Source

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

Gets the value of the IP_MULTICAST_TTL option for this socket.

For more information about this option, see UdpSocket::set_multicast_ttl_v4.

§Examples
let s = UdpSocket::bind("127.0.0.1:10000").unwrap();
s.set_multicast_ttl_v4(42)
    .expect("set_multicast_ttl_v4 call failed");
assert_eq!(s.multicast_ttl_v4().unwrap(), 42);
Source

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

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 that this may not have any effect on IPv6 sockets.

§Examples
let s = UdpSocket::bind("127.0.0.1:10000").unwrap();
s.set_multicast_ttl_v4(42)
    .expect("set_multicast_ttl_v4 call failed");
Source

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
let s = UdpSocket::bind("127.0.0.1:10000").unwrap();
s.set_ttl(42).expect("set_ttl call failed");
assert_eq!(s.ttl().unwrap(), 42);
Source

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
let s = UdpSocket::bind("127.0.0.1:10000").unwrap();
s.set_ttl(42).expect("set_ttl call failed");
Source

pub fn set_read_timeout(&self, dur: Option<Duration>) -> Result<(), ()>

Sets the read timeout to the timeout specified.

If the value specified is None, then read calls will block indefinitely. An Err is returned if the zero Duration is passed to this method.

§Examples
let s = UdpSocket::bind("127.0.0.1:10000").unwrap();
s.set_read_timeout(Some(Duration::from_secs(1))).unwrap();
Source

pub fn set_write_timeout(&self, dur: Option<Duration>) -> Result<(), ()>

Sets the write timeout to the timeout specified.

If the value specified is None, then write calls will block indefinitely. An Err is returned if the zero Duration is passed to this method.

let s = UdpSocket::bind("127.0.0.1:10000").unwrap();
s.set_write_timeout(Some(Duration::from_secs(1))).unwrap();
Source

pub fn read_timeout(&self) -> Option<Duration>

Returns the read timeout of this socket.

Source

pub fn write_timeout(&self) -> Option<Duration>

Returns the write timeout of this socket.

Source

pub async fn peek(&self, buf: &mut [u8]) -> Result<usize, ()>

Receives single datagram on the socket from the remote address to which it is connected, without removing the message from input queue. On success, returns the number of bytes peeked.

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.

To use this function, connect must have been called

§Examples
use glommio::{net::UdpSocket, LocalExecutor};

let ex = LocalExecutor::default();
ex.run(async move {
    let receiver = UdpSocket::bind("127.0.0.1:0").unwrap();
    let sender = UdpSocket::bind("127.0.0.1:0").unwrap();
    receiver
        .connect(sender.local_addr().unwrap())
        .await
        .unwrap();
    sender
        .send_to(&[1; 1], receiver.local_addr().unwrap())
        .await
        .unwrap();
    let mut buf = vec![0; 32];
    let sz = receiver.peek(&mut buf).await.unwrap();
    assert_eq!(sz, 1);
})
Source

pub async fn peek_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr), ()>

Receives a single datagram message on the socket, without removing it from the queue. 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.

Source

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

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

Source

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

Returns the socket address of the local half of this UDP connection.

Source

pub async 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.

To use this function, connect must have been called

§Examples
use glommio::{net::UdpSocket, LocalExecutor};

let ex = LocalExecutor::default();
ex.run(async move {
    let receiver = UdpSocket::bind("127.0.0.1:0").unwrap();
    let sender = UdpSocket::bind("127.0.0.1:0").unwrap();
    receiver
        .connect(sender.local_addr().unwrap())
        .await
        .unwrap();
    sender
        .send_to(&[1; 1], receiver.local_addr().unwrap())
        .await
        .unwrap();
    let mut buf = vec![0; 32];
    let sz = receiver.recv(&mut buf).await.unwrap();
    assert_eq!(sz, 1);
})
Source

pub async 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 glommio::{net::UdpSocket, LocalExecutor};

let ex = LocalExecutor::default();
ex.run(async move {
    let receiver = UdpSocket::bind("127.0.0.1:0").unwrap();
    let sender = UdpSocket::bind("127.0.0.1:0").unwrap();
    sender
        .send_to(&[1; 1], receiver.local_addr().unwrap())
        .await
        .unwrap();
    let mut buf = vec![0; 32];
    let (sz, addr) = receiver.recv_from(&mut buf).await.unwrap();
    assert_eq!(sz, 1);
    assert_eq!(addr, sender.local_addr().unwrap());
})
Source

pub async fn send_to<A: ToSocketAddrs>( &self, buf: &[u8], addr: A, ) -> Result<usize, ()>

Sends data on the socket to the given address. On success, returns the number of bytes written. Address type can be any implementor of 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.

§Examples
use glommio::{net::UdpSocket, LocalExecutor};

let ex = LocalExecutor::default();
ex.run(async move {
    let receiver = UdpSocket::bind("127.0.0.1:0").unwrap();
    let sender = UdpSocket::bind("127.0.0.1:0").unwrap();
    sender
        .send_to(&[1; 1], receiver.local_addr().unwrap())
        .await
        .unwrap();
    let mut buf = vec![0; 32];
    let (sz, addr) = receiver.recv_from(&mut buf).await.unwrap();
    assert_eq!(sz, 1);
    assert_eq!(addr, sender.local_addr().unwrap());
})
Source

pub async 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 glommio::{net::UdpSocket, LocalExecutor};

let ex = LocalExecutor::default();
ex.run(async move {
    let receiver = UdpSocket::bind("127.0.0.1:0").unwrap();
    let sender = UdpSocket::bind("127.0.0.1:0").unwrap();
    sender
        .connect(receiver.local_addr().unwrap())
        .await
        .unwrap();
    sender.send(&[1; 1]).await.unwrap();
})

[UdpSocket::connect]: UdpSocket::connect

Trait Implementations§

Source§

impl AsRawFd for UdpSocket

Source§

fn as_raw_fd(&self) -> RawFd

Extracts the raw file descriptor. 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 From<Socket> for UdpSocket

Source§

fn from(socket: Socket) -> UdpSocket

Converts to this type from the input type.
Source§

impl FromRawFd for UdpSocket

Source§

unsafe fn from_raw_fd(fd: RawFd) -> Self

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

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> 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> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

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

Initializes a with the given initializer. Read more
Source§

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

Dereferences the given pointer. Read more
Source§

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

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. 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