How to obtain hwaddr of first ethernet card?
And how to list all interfaces?
On Unix-like OS, /sys/class/net/
contains the symlinks to the available interfaces on your machine and the MAC address of an interface is written in a file like /sys/class/net/eth0/address
On windows, I guess you have to parse the output of an external command like ipconfig
to pick up your desired information.
A demo:
use std::fs;
use std::io::Read;
use std::path::Path;
fn main() {
let net = Path::new("/sys/class/net");
let entry = fs::read_dir(net).expect("Error");
// a bit cubersome :/
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>>();
println!("Available interfaces: {:?}", ifaces);
let iface = net.join(ifaces[0].as_str()).join("address");
let mut f = fs::File::open(iface).expect("Failed");
let mut macaddr = String::new();
f.read_to_string(&mut macaddr).expect("Error");
println!("MAC address: {}", macaddr);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With