1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#![deny(missing_docs)]
#[cfg(target_os = "windows")]
extern crate winapi;
#[cfg(target_os = "linux")]
extern crate nix;
#[cfg(target_os = "windows")]
#[path = "windows/mod.rs"]
mod os;
#[cfg(target_os = "linux")]
#[path = "linux.rs"]
mod os;
#[derive(Debug)]
pub enum MacAddressError {
InternalError,
}
#[cfg(target_os = "linux")]
impl From<nix::Error> for MacAddressError {
fn from(_: nix::Error) -> MacAddressError {
MacAddressError::InternalError
}
}
impl std::fmt::Display for MacAddressError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
use MacAddressError::*;
write!(
f,
"{}",
match self {
&InternalError => "Internal API error",
}
)?;
Ok(())
}
}
impl std::error::Error for MacAddressError {
fn description(&self) -> &str {
use MacAddressError::*;
match self {
&InternalError => "Internal API error",
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct MacAddress {
bytes: [u8; 6],
}
pub fn get_mac_address() -> Result<Option<MacAddress>, MacAddressError> {
let bytes = os::get_mac()?;
Ok(match bytes {
Some(b) => Some(MacAddress { bytes: b }),
None => None,
})
}
pub fn mac_address_by_name(name: &str) -> Result<Option<MacAddress>, MacAddressError> {
let bytes = os::get_mac_from_name(name)?;
Ok(match bytes {
Some(b) => Some(MacAddress { bytes: b }),
None => None,
})
}
impl MacAddress {
pub fn bytes(&self) -> [u8; 6] {
self.bytes
}
}
impl std::fmt::Display for MacAddress {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let _ = write!(
f,
"{:<02X}:{:<02X}:{:<02X}:{:<02X}:{:<02X}:{:<02X}",
self.bytes[0],
self.bytes[1],
self.bytes[2],
self.bytes[3],
self.bytes[4],
self.bytes[5]
);
Ok(())
}
}