ssdp/net/
packet.rs

1use std::io::{self, Error, ErrorKind};
2use std::net::{UdpSocket, SocketAddr};
3use std::fmt;
4
5/// Maximum length for packets received on a `PacketReceiver`.
6pub const MAX_PCKT_LEN: usize = 1500;
7
8/// A `PacketReceiver` that abstracts over a network socket and reads full packets
9/// from the connection. Packets received from this connection are assumed to
10/// be no larger than what the typical MTU would be on a standard router.
11///
12/// See `net::packet::MAX_PCKT_LEN`.
13pub struct PacketReceiver(UdpSocket);
14
15impl PacketReceiver {
16    /// Create a new PacketReceiver from the given UdpSocket.
17    pub fn new(udp: UdpSocket) -> PacketReceiver {
18        PacketReceiver(udp)
19    }
20
21    /// Receive a packet from the underlying connection.
22    pub fn recv_pckt(&self) -> io::Result<(Vec<u8>, SocketAddr)> {
23        let mut pckt_buf = vec![0u8; MAX_PCKT_LEN];
24
25        let (size, addr) = try!(self.0.recv_from(&mut pckt_buf));
26
27        // Check For Something That SHOULD NEVER Occur.
28        if size > pckt_buf.len() {
29            Err(Error::new(ErrorKind::Other, "UdpSocket Reported Receive Length Greater Than Buffer"))
30        } else {
31            // `truncate` does not reallocate the vec's backing storage
32            pckt_buf.truncate(size);
33
34            Ok((pckt_buf, addr))
35        }
36    }
37}
38
39impl fmt::Display for PacketReceiver {
40    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
41        match self.0.local_addr() {
42            Ok(addr) => write!(f, "{}", addr),
43            Err(err) => write!(f, "{}", err),
44        }
45    }
46}