Skip to content

Instantly share code, notes, and snippets.

@shakram02
Created September 7, 2019 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shakram02/fa426f8a1145d971d04a336e15a9e4f6 to your computer and use it in GitHub Desktop.
Save shakram02/fa426f8a1145d971d04a336e15a9e4f6 to your computer and use it in GitHub Desktop.
get MAC addresses of all interfaces on a Linux-ish system, returns a hashmap of (iface_name, mac_addr) without any external dependencies
use std::collections::HashMap;
use std::fs;
use std::io::Read;
use std::path::Path;
fn get_macs() -> HashMap<String, String> {
// cat the /sys/class/net/iface/address to get the MAC
// based on: https://stackoverflow.com/questions/26346575/how-to-get-mac-address-in-rust
let net = Path::new("/sys/class/net");
let entry = fs::read_dir(net).expect("Error");
let ifaces = entry
.filter_map(|p| p.ok())
.map(|p| p.path().file_name().expect("Error").to_os_string())
.filter_map(|s| s.into_string().ok())
.collect::<Vec<String>>();
let macs: Vec<String> = ifaces
.iter()
.map(|iface| net.join(iface.as_str()).join("address"))
.map(|addr_path| fs::File::open(addr_path).unwrap())
.map(|mut addr_file| {
let mut macaddr = String::new();
addr_file.read_to_string(&mut macaddr).unwrap();
macaddr.trim_end().to_string()
})
.collect();
let mut iface_mac = HashMap::new();
for (key, value) in ifaces.into_iter().zip(macs) {
println!("iface {} [{}]", key, value);
iface_mac.insert(key, value);
}
iface_mac
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment