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    pub ip: IpAddr,
22    pub port: u16,
23}
24
25impl Default for PeerAddress {
26    fn default() -> Self {
27        PeerAddress {
28            ip: IpAddr::V4(Ipv4Addr::from(0)),
29            port: 0,
30        }
31    }
32}
33
34impl fmt::Display for PeerAddress {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        match self.ip {
37            IpAddr::V4(_) => write!(f, "{}:{}", self.ip, self.port),
38            IpAddr::V6(_) => write!(f, "[{}]:{}", self.ip, self.port),
39        }
40    }
41}
42
43impl Setter for PeerAddress {
44    /// Adds `XOR-PEER-ADDRESS` to message.
45    fn add_to(&self, m: &mut Message) -> Result<()> {
46        let a = XorMappedAddress {
47            ip: self.ip,
48            port: self.port,
49        };
50        a.add_to_as(m, ATTR_XOR_PEER_ADDRESS)
51    }
52}
53
54impl Getter for PeerAddress {
55    /// Decodes `XOR-PEER-ADDRESS` from message.
56    fn get_from(&mut self, m: &Message) -> Result<()> {
57        let mut a = XorMappedAddress::default();
58        a.get_from_as(m, ATTR_XOR_PEER_ADDRESS)?;
59        self.ip = a.ip;
60        self.port = a.port;
61        Ok(())
62    }
63}
64
65/// `PeerAddress` implements `XOR-PEER-ADDRESS` attribute.
66///
67/// The `XOR-PEER-ADDRESS` specifies the address and port of the peer as
68/// seen from the TURN server. (For example, the peer's server-reflexive
69/// transport address if the peer is behind a NAT.)
70///
71/// [RFC 5766 Section 14.3](https://www.rfc-editor.org/rfc/rfc5766#section-14.3).
72pub type XorPeerAddress = PeerAddress;