Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get MAC-address in Rust?

How to obtain hwaddr of first ethernet card?

And how to list all interfaces?

like image 249
Alex Raeder Avatar asked Oct 13 '14 18:10

Alex Raeder


1 Answers

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);
}
like image 110
knight42 Avatar answered Oct 13 '22 04:10

knight42