webrtc_util/conn/
mod.rs

1pub mod conn_bridge;
2pub mod conn_disconnected_packet;
3pub mod conn_pipe;
4pub mod conn_udp;
5pub mod conn_udp_listener;
6
7#[cfg(test)]
8mod conn_bridge_test;
9#[cfg(test)]
10mod conn_pipe_test;
11#[cfg(test)]
12mod conn_test;
13
14//TODO: remove this conditional test
15#[cfg(not(target_os = "windows"))]
16#[cfg(test)]
17mod conn_udp_listener_test;
18
19use std::net::SocketAddr;
20use std::sync::Arc;
21
22use async_trait::async_trait;
23use tokio::net::ToSocketAddrs;
24
25use crate::error::Result;
26
27#[async_trait]
28pub trait Conn {
29    async fn connect(&self, addr: SocketAddr) -> Result<()>;
30    async fn recv(&self, buf: &mut [u8]) -> Result<usize>;
31    async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>;
32    async fn send(&self, buf: &[u8]) -> Result<usize>;
33    async fn send_to(&self, buf: &[u8], target: SocketAddr) -> Result<usize>;
34    fn local_addr(&self) -> Result<SocketAddr>;
35    fn remote_addr(&self) -> Option<SocketAddr>;
36    async fn close(&self) -> Result<()>;
37    fn as_any(&self) -> &(dyn std::any::Any + Send + Sync);
38}
39
40/// A Listener is a generic network listener for connection-oriented protocols.
41/// Multiple connections may invoke methods on a Listener simultaneously.
42#[async_trait]
43pub trait Listener {
44    /// accept waits for and returns the next connection to the listener.
45    async fn accept(&self) -> Result<(Arc<dyn Conn + Send + Sync>, SocketAddr)>;
46
47    /// close closes the listener.
48    /// Any blocked accept operations will be unblocked and return errors.
49    async fn close(&self) -> Result<()>;
50
51    /// addr returns the listener's network address.
52    async fn addr(&self) -> Result<SocketAddr>;
53}
54
55pub async fn lookup_host<T>(use_ipv4: bool, host: T) -> Result<SocketAddr>
56where
57    T: ToSocketAddrs,
58{
59    for remote_addr in tokio::net::lookup_host(host).await? {
60        if (use_ipv4 && remote_addr.is_ipv4()) || (!use_ipv4 && remote_addr.is_ipv6()) {
61            return Ok(remote_addr);
62        }
63    }
64
65    Err(std::io::Error::new(
66        std::io::ErrorKind::Other,
67        format!(
68            "No available {} IP address found!",
69            if use_ipv4 { "ipv4" } else { "ipv6" },
70        ),
71    )
72    .into())
73}