rcv_from returns a packet instead of filling a buffer

This commit is contained in:
Jeremy Wall 2021-01-25 19:00:09 -05:00
parent 8971625151
commit e850bf0236
3 changed files with 23 additions and 12 deletions

View File

@ -98,7 +98,6 @@ impl From<IcmpSocket4> for EchoSocket4 {
pub struct EchoSocket6 { pub struct EchoSocket6 {
sequence: u16, sequence: u16,
buf: Vec<u8>,
inner: IcmpSocket6, inner: IcmpSocket6,
} }
@ -106,7 +105,7 @@ impl EchoSocket6 {
pub fn new(sock: IcmpSocket6) -> Self { pub fn new(sock: IcmpSocket6) -> Self {
// TODO(jwall): How to set ICMPv6 filters. // TODO(jwall): How to set ICMPv6 filters.
EchoSocket6{inner:sock, sequence: 0, buf: Vec::with_capacity(512)} EchoSocket6{inner:sock, sequence: 0}
} }
pub fn set_max_hops(&mut self, hops: u32) { pub fn set_max_hops(&mut self, hops: u32) {
@ -121,12 +120,8 @@ impl EchoSocket6 {
} }
pub fn recv_ping(&mut self) -> std::io::Result<EchoResponse> { pub fn recv_ping(&mut self) -> std::io::Result<EchoResponse> {
self.buf.resize(512, 0); let pkt = self.inner.rcv_from()?;
let bytes_read = self.inner.rcv_from(&mut self.buf)?; Ok(pkt.try_into()?)
match Icmpv6Packet::parse(&self.buf[0..bytes_read]) {
Ok(p) => return Ok(p.try_into()?),
Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, format!("Malformed ICMP Response: {:?}", e))),
};
} }
} }

View File

@ -340,12 +340,27 @@ impl std::fmt::Display for Icmpv6PacketBuildError {
} }
} }
impl std::fmt::Display for PacketParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", match self {
PacketParseError::PacketTooSmall(c) => format!("Packet Too Small size: {}", c),
PacketParseError::UnrecognizedICMPType => "UnrecognizedIcmpType".to_owned(),
})
}
}
impl From<Icmpv6PacketBuildError> for std::io::Error { impl From<Icmpv6PacketBuildError> for std::io::Error {
fn from(err: Icmpv6PacketBuildError) -> Self { fn from(err: Icmpv6PacketBuildError) -> Self {
std::io::Error::new(std::io::ErrorKind::Other, format!("{}", err)) std::io::Error::new(std::io::ErrorKind::Other, format!("{}", err))
} }
} }
impl From<PacketParseError> for std::io::Error {
fn from(err: PacketParseError) -> Self {
std::io::Error::new(std::io::ErrorKind::Other, format!("{}", err))
}
}
#[cfg(test)] #[cfg(test)]
mod checksum_tests { mod checksum_tests {
use super::*; use super::*;

View File

@ -108,10 +108,11 @@ impl IcmpSocket6 {
Ok(()) Ok(())
} }
// TODO(jwall): This should return a packet not bytes. pub fn rcv_from(&self) -> std::io::Result<Icmpv6Packet> {
pub fn rcv_from(&self, buf: &mut [u8]) -> std::io::Result<usize> { let mut buf = vec![0; 512];
let (read_count, _addr) = self.inner.recv_from(buf)?; let (read_count, _addr) = self.inner.recv_from(&mut buf)?;
Ok(read_count) let pkt = Icmpv6Packet::parse(&buf[0..read_count])?;
Ok(pkt)
} }
} }