Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Network programming 如何在Rust中获取MAC地址?_Network Programming_Hardware_Rust_Mac Address - Fatal编程技术网

Network programming 如何在Rust中获取MAC地址?

Network programming 如何在Rust中获取MAC地址?,network-programming,hardware,rust,mac-address,Network Programming,Hardware,Rust,Mac Address,如何获得第一张以太网卡的hwaddr 以及如何列出所有接口?在类Unix操作系统上,/sys/class/net/包含指向计算机上可用接口的符号链接,接口的MAC地址写在类似/sys/class/net/eth0/address 在windows上,我想您必须解析外部命令的输出,如ipconfig,以获取所需的信息 演示: use std::fs; use std::io::Read; use std::path::Path; fn main() { let net = Path::n

如何获得第一张以太网卡的hwaddr


以及如何列出所有接口?

在类Unix操作系统上,
/sys/class/net/
包含指向计算机上可用接口的符号链接,接口的MAC地址写在类似
/sys/class/net/eth0/address

在windows上,我想您必须解析外部命令的输出,如
ipconfig
,以获取所需的信息

演示:

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);
}
使用std::fs;
使用std::io::Read;
使用std::path::path;
fn main(){
让net=Path::new(“/sys/class/net”);
let entry=fs::read_dir(net).expect(“Error”);
//有点像立方体:/
设ifaces=entry.filter_map(| p | p.ok())
.map(| p | p.path().file_name().expect(“Error”).to_os_string())
.filter_map(|s|s.进入_字符串().ok())
收集::();
println!(“可用接口:{:?}”,ifaces);
让iface=net.join(ifaces[0].as_str()).join(“地址”);
让mut f=fs::File::open(iface).expect(“失败”);
让mut macaddr=String::new();
f、 读取到字符串(&mut macaddr).expect(“错误”);
println!(“MAC地址:{}”,macaddr);
}

您希望在什么平台上执行此操作?我不相信有任何跨平台的库可以做到这一点;打印getnode()是的,这是跨平台的方法。@Brian,在第一行中,我需要在linux上完成。在RaspberryPi上的ArchLinux的第一行中。你的第一句话是错误的:在Linux上,你可以使用
/sys
,或者更具体地说,在一个带有
sysfs
的系统上,Linux就是其中之一。例如,BSD或Mac没有
sysfs
,因此无法访问
/sys