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