webrtc_turn/relay/
relay_static.rs

1use super::*;
2use crate::errors::*;
3
4use std::net::IpAddr;
5use util::vnet::net::*;
6
7use async_trait::async_trait;
8
9// RelayAddressGeneratorStatic can be used to return static IP address each time a relay is created.
10// This can be used when you have a single static IP address that you want to use
11pub struct RelayAddressGeneratorStatic {
12    // RelayAddress is the IP returned to the user when the relay is created
13    pub relay_address: IpAddr,
14
15    // Address is passed to Listen/ListenPacket when creating the Relay
16    pub address: String,
17
18    pub net: Arc<Net>,
19}
20
21#[async_trait]
22impl RelayAddressGenerator for RelayAddressGeneratorStatic {
23    // validate confirms that the RelayAddressGenerator is properly initialized
24    fn validate(&self) -> Result<(), Error> {
25        if self.address.is_empty() {
26            Err(ERR_LISTENING_ADDRESS_INVALID.to_owned())
27        } else {
28            Ok(())
29        }
30    }
31
32    // Allocate a PacketConn (UDP) RelayAddress
33    async fn allocate_conn(
34        &self,
35        use_ipv4: bool,
36        requested_port: u16,
37    ) -> Result<(Arc<dyn Conn + Send + Sync>, SocketAddr), Error> {
38        let addr = self
39            .net
40            .resolve_addr(use_ipv4, &format!("{}:{}", self.address, requested_port))
41            .await?;
42        let conn = self.net.bind(addr).await?;
43        let mut relay_addr = conn.local_addr().await?;
44        relay_addr.set_ip(self.relay_address);
45        return Ok((conn, relay_addr));
46    }
47}