use std::net::Ipv4Addr;
use std::path::Path;
use crate::error::{Error, Result};
use crate::util::parse;
#[derive(Debug)]
pub struct ArpEntry {
pub ip: Ipv4Addr,
pub hw_type: u16,
pub flags: u16,
pub mac: [u8; 6],
pub device: Box<str>,
}
pub fn arp() -> impl Iterator<Item = Result<ArpEntry>> {
let path = Path::new("/proc/net/arp");
let bytes = match parse::read_file(path) {
Ok(b) => b,
Err(e) => return vec![Err(e)].into_iter(),
};
let mut entries = Vec::new();
for line in bytes
.split(|&b| b == b'\n')
.filter(|l| !l.is_empty())
.skip(1)
{
let fields = parse::SplitFields::<6>::new(line);
if fields.len() < 6 {
entries.push(Err(Error::Parse {
path: path.to_path_buf(),
line: 0,
msg: "not enough fields",
}));
continue;
}
let ip_str = std::str::from_utf8(fields[0]).unwrap_or("");
let ip: Ipv4Addr = match ip_str.parse() {
Ok(addr) => addr,
Err(_) => {
entries.push(Err(Error::Parse {
path: path.to_path_buf(),
line: 0,
msg: "invalid IPv4 address",
}));
continue;
}
};
let hw_type = parse::parse_hex_fast(fields[1].get(2..).unwrap_or(fields[1])) as u16;
let flags = parse::parse_hex_fast(fields[2].get(2..).unwrap_or(fields[2])) as u16;
let mac = parse_mac(fields[3]);
let device = std::str::from_utf8(fields[5])
.unwrap_or("")
.to_string()
.into_boxed_str();
entries.push(Ok(ArpEntry {
ip,
hw_type,
flags,
mac,
device,
}));
}
entries.into_iter()
}
fn parse_mac(bytes: &[u8]) -> [u8; 6] {
if bytes.len() != 17
|| bytes[2] != b':'
|| bytes[5] != b':'
|| bytes[8] != b':'
|| bytes[11] != b':'
|| bytes[14] != b':'
{
return [0; 6];
}
let mut mac = [0u8; 6];
for i in 0..6 {
mac[i] = parse::parse_hex_fast(&bytes[i * 3..i * 3 + 2]) as u8;
}
mac
}