webrtc_turn/proto/
peeraddr.rs

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