Skip to main content

rtc_turn/proto/
peeraddr.rs

1#[cfg(test)]
2mod peeraddr_test;
3
4use std::fmt;
5use std::net::{IpAddr, Ipv4Addr};
6
7use shared::error::Result;
8use stun::attributes::*;
9use stun::message::*;
10use stun::xoraddr::*;
11
12/// `PeerAddress` implements `XOR-PEER-ADDRESS` attribute.
13///
14/// The `XOR-PEER-ADDRESS` specifies the address and port of the peer as
15/// seen from the TURN server. (For example, the peer's server-reflexive
16/// transport address if the peer is behind a NAT.)
17///
18/// [RFC 5766 Section 14.3](https://www.rfc-editor.org/rfc/rfc5766#section-14.3).
19#[derive(PartialEq, Eq, Debug)]
20pub struct PeerAddress {
21    /// The peer IP address.
22    pub ip: IpAddr,
23    /// The peer port.
24    pub port: u16,
25}
26
27impl Default for PeerAddress {
28    fn default() -> Self {
29        PeerAddress {
30            ip: IpAddr::V4(Ipv4Addr::from(0)),
31            port: 0,
32        }
33    }
34}
35
36impl fmt::Display for PeerAddress {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match self.ip {
39            IpAddr::V4(_) => write!(f, "{}:{}", self.ip, self.port),
40            IpAddr::V6(_) => write!(f, "[{}]:{}", self.ip, self.port),
41        }
42    }
43}
44
45impl Setter for PeerAddress {
46    /// Adds `XOR-PEER-ADDRESS` to message.
47    fn add_to(&self, m: &mut Message) -> Result<()> {
48        let a = XorMappedAddress {
49            ip: self.ip,
50            port: self.port,
51        };
52        a.add_to_as(m, ATTR_XOR_PEER_ADDRESS)
53    }
54}
55
56impl Getter for PeerAddress {
57    /// Decodes `XOR-PEER-ADDRESS` from message.
58    fn get_from(&mut self, m: &Message) -> Result<()> {
59        let mut a = XorMappedAddress::default();
60        a.get_from_as(m, ATTR_XOR_PEER_ADDRESS)?;
61        self.ip = a.ip;
62        self.port = a.port;
63        Ok(())
64    }
65}
66
67/// `PeerAddress` implements `XOR-PEER-ADDRESS` attribute.
68///
69/// The `XOR-PEER-ADDRESS` specifies the address and port of the peer as
70/// seen from the TURN server. (For example, the peer's server-reflexive
71/// transport address if the peer is behind a NAT.)
72///
73/// [RFC 5766 Section 14.3](https://www.rfc-editor.org/rfc/rfc5766#section-14.3).
74pub type XorPeerAddress = PeerAddress;