Skip to main content

net_wire/arp/
ethernet.rs

1use crate::error::ParseError;
2use crate::ethernet::{
3    address::MacAddress,
4    ether_type::EtherType,
5    frame::{EthernetFrame, EthernetFrameMut},
6};
7
8use super::packet::{ArpPacket, ArpPacketMut};
9use super::types::ArpHardwareType;
10
11impl<'a> EthernetFrame<'a> {
12    /// Parses an ARP payload only when this frame's EtherType is ARP.
13    #[inline]
14    pub fn arp(&self) -> Result<Option<ArpPacket<'a>>, ParseError> {
15        if self.ether_type() != EtherType::ARP {
16            return Ok(None);
17        }
18        ArpPacket::parse(self.payload()).map(Some)
19    }
20}
21
22impl<'a> EthernetFrameMut<'a> {
23    /// Parses a mutable ARP payload only when this frame's EtherType is ARP.
24    #[inline]
25    pub fn arp_mut(&mut self) -> Result<Option<ArpPacketMut<'_>>, ParseError> {
26        if self.ether_type() != EtherType::ARP {
27            return Ok(None);
28        }
29        ArpPacketMut::parse(self.payload_mut()).map(Some)
30    }
31}
32
33impl<'a> ArpPacket<'a> {
34    /// Returns the sender MAC address only for Ethernet hardware with a six-octet address.
35    #[inline]
36    pub fn sender_mac_address(&self) -> Option<MacAddress> {
37        if self.hardware_type() != ArpHardwareType::ETHERNET
38            || self.sender_hardware_address().len() != 6
39        {
40            return None;
41        }
42        Some(MacAddress::new(
43            self.sender_hardware_address()
44                .try_into()
45                .expect("checked address length"),
46        ))
47    }
48    /// Returns the target MAC address only for Ethernet hardware with a six-octet address.
49    #[inline]
50    pub fn target_mac_address(&self) -> Option<MacAddress> {
51        if self.hardware_type() != ArpHardwareType::ETHERNET
52            || self.target_hardware_address().len() != 6
53        {
54            return None;
55        }
56        Some(MacAddress::new(
57            self.target_hardware_address()
58                .try_into()
59                .expect("checked address length"),
60        ))
61    }
62}