mac_address-1.1.5/.cargo_vcs_info.json0000644000000001360000000000100133050ustar { "git": { "sha1": "42af337bdcd912603fb19f8ca6fbdefa080d22e7" }, "path_in_vcs": "" }mac_address-1.1.5/.gitignore000064400000000000000000000000370072674642500141150ustar 00000000000000 /target **/*.rs.bk Cargo.lock mac_address-1.1.5/Cargo.lock0000644000000107550000000000100112700ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "autocfg" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "cc" version = "1.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "itoa" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" [[package]] name = "libc" version = "0.2.142" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a987beff54b60ffa6d51982e1aa1146bc42f19bd26be28b0586f252fccf5317" [[package]] name = "mac_address" version = "1.1.5" dependencies = [ "nix", "serde", "serde_json", "serde_test", "winapi", ] [[package]] name = "memoffset" version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" dependencies = [ "autocfg", ] [[package]] name = "nix" version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f3790c00a0150112de0f4cd161e3d7fc4b2d8a5542ffc35f099a2562aecb35c" dependencies = [ "bitflags", "cc", "cfg-if", "libc", "memoffset", ] [[package]] name = "proc-macro2" version = "1.0.56" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b63bdb0cd06f1f4dedf69b254734f9b45af66e4a031e42a7480257d9898b435" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc" dependencies = [ "proc-macro2", ] [[package]] name = "ryu" version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041" [[package]] name = "serde" version = "1.0.160" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb2f3770c8bce3bcda7e149193a069a0f4365bda1fa5cd88e03bca26afc1216c" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.160" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "291a097c63d8497e00160b166a967a4a79c64f3facdd01cbd7502231688d77df" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "serde_test" version = "1.0.160" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c95a500e3923258f7fc3a16bf29934e403aef5ca1096e184d85e3b1926675e8" dependencies = [ "serde", ] [[package]] name = "syn" version = "2.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a34fcf3e8b60f57e6a14301a2e916d323af98b0ea63c599441eec8558660c822" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "unicode-ident" version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" mac_address-1.1.5/Cargo.toml0000644000000024370000000000100113110ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "mac_address" version = "1.1.5" authors = ["rep-nop "] exclude = ["/.github/"] description = "Cross-platform retrieval of a network interface MAC address." readme = "README.md" keywords = [ "mac", "address", "network", "interface", ] license = "MIT OR Apache-2.0" repository = "https://github.com/rep-nop/mac_address" [dependencies.serde] version = "1.0.117" features = ["derive"] optional = true [dev-dependencies.serde_json] version = "1.0.59" [dev-dependencies.serde_test] version = "1.0.117" [target."cfg(any(target_os = \"linux\", target_os = \"macos\", target_os = \"freebsd\", target_os = \"openbsd\"))".dependencies.nix] version = "0.23.1" [target."cfg(windows)".dependencies.winapi] version = "0.3" features = [ "winerror", "ws2def", "iphlpapi", ] mac_address-1.1.5/Cargo.toml.orig000064400000000000000000000014050072674642500150140ustar 00000000000000[package] name = "mac_address" version = "1.1.5" authors = ["rep-nop "] edition = "2018" description = "Cross-platform retrieval of a network interface MAC address." repository = "https://github.com/rep-nop/mac_address" readme = "README.md" license = "MIT OR Apache-2.0" exclude = ["/.github/"] keywords = ["mac", "address", "network", "interface"] [dependencies] serde = { version = "1.0.117", features = ["derive"], optional = true } [target.'cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "openbsd"))'.dependencies] nix = "0.23.1" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3", features = ["winerror", "ws2def", "iphlpapi"] } [dev-dependencies] serde_test = "1.0.117" serde_json = "1.0.59" mac_address-1.1.5/LICENSE-APACHE2.0000064400000000000000000000261200072674642500142720ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018 Wesley Norris Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. mac_address-1.1.5/LICENSE-MIT000064400000000000000000000020470072674642500135640ustar 00000000000000Copyright © 2018 Wesley Norris Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.mac_address-1.1.5/README.md000064400000000000000000000015100072674642500134010ustar 00000000000000# `mac_address` [![crates.io](https://img.shields.io/crates/v/mac_address.svg)](https://crates.io/crates/mac_address) [![Released API docs](https://docs.rs/mac_address/badge.svg)](https://docs.rs/mac_address) `mac_address` provides a cross platform way to retrieve the [MAC address](https://en.wikipedia.org/wiki/MAC_address) of network hardware. Supported platforms: Linux, Windows, MacOS, FreeBSD, OpenBSD ## Example ```rust extern crate mac_address; use mac_address::get_mac_address; fn main() { match get_mac_address() { Ok(Some(ma)) => { println!("MAC addr = {}", ma); println!("bytes = {:?}", ma.bytes()); } Ok(None) => println!("No MAC address found."), Err(e) => println!("{:?}", e), } } ``` ## License `mac_address` is licensed under both MIT and Apache 2.0 mac_address-1.1.5/examples/iterator.rs000064400000000000000000000002150072674642500161400ustar 00000000000000use mac_address::MacAddressIterator; fn main() { for addr in MacAddressIterator::new().unwrap() { println!("{}", addr); } } mac_address-1.1.5/examples/lookup.rs000064400000000000000000000011440072674642500156220ustar 00000000000000use mac_address::mac_address_by_name; fn main() { #[cfg(any(target_os = "linux", target_os = "macos"))] let name = "eth0"; #[cfg(any(target_os = "freebsd"))] let name = "em0"; #[cfg(any(target_os = "openbsd"))] let name = "fxp0"; #[cfg(target_os = "windows")] let name = "Ethernet"; match mac_address_by_name(name) { Ok(Some(ma)) => { println!("MAC addr of {} = {}", name, ma); println!("bytes = {:?}", ma.bytes()); } Ok(None) => println!("Interface \"{}\" not found", name), Err(e) => println!("{:?}", e), } } mac_address-1.1.5/examples/simple.rs000064400000000000000000000004640072674642500156060ustar 00000000000000use mac_address::get_mac_address; fn main() { match get_mac_address() { Ok(Some(ma)) => { println!("MAC addr = {}", ma); println!("bytes = {:?}", ma.bytes()); } Ok(None) => println!("No MAC address found."), Err(e) => println!("{:?}", e), } } mac_address-1.1.5/src/iter/linux.rs000064400000000000000000000016240072674642500153670ustar 00000000000000use crate::{MacAddress, MacAddressError}; use nix::{ifaddrs, sys::socket::SockAddr}; /// An iterator over all available MAC addresses on the system. pub struct MacAddressIterator { iter: std::iter::FilterMap< ifaddrs::InterfaceAddressIterator, fn(ifaddrs::InterfaceAddress) -> Option, >, } impl MacAddressIterator { /// Creates a new `MacAddressIterator`. pub fn new() -> Result { Ok(Self { iter: ifaddrs::getifaddrs()?.filter_map(filter_macs), }) } } fn filter_macs(intf: ifaddrs::InterfaceAddress) -> Option { if let SockAddr::Link(link) = intf.address? { Some(MacAddress::new(link.addr())) } else { None } } impl Iterator for MacAddressIterator { type Item = MacAddress; fn next(&mut self) -> Option { self.iter.next() } } mac_address-1.1.5/src/iter/mod.rs000064400000000000000000000004040072674642500150020ustar 00000000000000#[cfg(target_os = "windows")] #[path = "windows.rs"] mod internal; #[cfg(any( target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "openbsd" ))] #[path = "linux.rs"] mod internal; pub use internal::MacAddressIterator; mac_address-1.1.5/src/iter/windows.rs000064400000000000000000000022770072674642500157270ustar 00000000000000use crate::os; use crate::{MacAddress, MacAddressError}; use winapi::um::iptypes::PIP_ADAPTER_ADDRESSES; /// An iterator over all available MAC addresses on the system. pub struct MacAddressIterator { // So we don't UAF during iteration. _buffer: os::AdaptersList, ptr: PIP_ADAPTER_ADDRESSES, } impl MacAddressIterator { /// Creates a new `MacAddressIterator`. pub fn new() -> Result { let adapters = os::get_adapters()?; let ptr = unsafe { adapters.ptr() }; Ok(Self { _buffer: adapters, ptr, }) } } impl Iterator for MacAddressIterator { type Item = MacAddress; fn next(&mut self) -> Option { if self.ptr.is_null() { None } else { let bytes = unsafe { os::convert_mac_bytes(self.ptr) }; #[cfg(target_pointer_width = "32")] { self.ptr = unsafe { self.ptr.read_unaligned().Next }; } #[cfg(not(target_pointer_width = "32"))] { self.ptr = unsafe { (*self.ptr).Next }; } Some(MacAddress::new(bytes)) } } } mac_address-1.1.5/src/lib.rs000064400000000000000000000172710072674642500140400ustar 00000000000000//! `mac_address` provides a cross platform way to retrieve the MAC address of //! network hardware. See [the Wikipedia //! entry](https://en.wikipedia.org/wiki/MAC_address) for more information. //! //! Supported platforms: Linux, Windows, MacOS, FreeBSD #![deny(missing_docs)] #[cfg(target_os = "windows")] #[path = "windows.rs"] mod os; #[cfg(any( target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "openbsd" ))] #[path = "linux.rs"] mod os; mod iter; pub use iter::MacAddressIterator; /// Possible errors when attempting to retrieve a MAC address. /// /// Eventually will expose more detailed error information. #[derive(Debug)] pub enum MacAddressError { /// Signifies an internal API error has occurred. InternalError, } #[cfg(any( target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "openbsd" ))] impl From 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 { f.write_str(match self { MacAddressError::InternalError => "Internal API error", }) } } impl std::error::Error for MacAddressError {} /// An error that may occur when parsing a MAC address string. #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum MacParseError { /// Parsing of the MAC address contained an invalid digit. InvalidDigit, /// The MAC address did not have the correct length. InvalidLength, } impl std::fmt::Display for MacParseError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str(match *self { MacParseError::InvalidDigit => "invalid digit", MacParseError::InvalidLength => "invalid length", }) } } impl std::error::Error for MacParseError {} /// Contains the individual bytes of the MAC address. #[derive(Debug, Clone, Copy, PartialEq, Default, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde", derive(serde::Deserialize))] #[cfg_attr(feature = "serde", serde(try_from = "std::borrow::Cow<'_, str>"))] pub struct MacAddress { bytes: [u8; 6], } impl MacAddress { /// Creates a new `MacAddress` struct from the given bytes. pub fn new(bytes: [u8; 6]) -> MacAddress { MacAddress { bytes } } } impl From<[u8; 6]> for MacAddress { fn from(v: [u8; 6]) -> Self { MacAddress::new(v) } } #[cfg(feature = "serde")] impl serde::Serialize for MacAddress { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { serializer.collect_str(self) } } /// Calls the OS-specific function for retrieving the MAC address of the first /// network device containing one, ignoring local-loopback. pub fn get_mac_address() -> Result, MacAddressError> { let bytes = os::get_mac(None)?; Ok(bytes.map(|b| MacAddress { bytes: b })) } /// Attempts to look up the MAC address of an interface via the specified name. /// **NOTE**: On Windows, this uses the `FriendlyName` field of the adapter, which /// is the same name shown in the "Network Connections" Control Panel screen. pub fn mac_address_by_name(name: &str) -> Result, MacAddressError> { let bytes = os::get_mac(Some(name))?; Ok(bytes.map(|b| MacAddress { bytes: b })) } /// Attempts to look up the interface name via MAC address. pub fn name_by_mac_address(mac: &MacAddress) -> Result, MacAddressError> { os::get_ifname(&mac.bytes) } impl MacAddress { /// Returns the array of MAC address bytes. pub fn bytes(self) -> [u8; 6] { self.bytes } } impl std::str::FromStr for MacAddress { type Err = MacParseError; fn from_str(input: &str) -> Result { let mut array = [0u8; 6]; let mut nth = 0; for byte in input.split(|c| c == ':' || c == '-') { if nth == 6 { return Err(MacParseError::InvalidLength); } array[nth] = u8::from_str_radix(byte, 16).map_err(|_| MacParseError::InvalidDigit)?; nth += 1; } if nth != 6 { return Err(MacParseError::InvalidLength); } Ok(MacAddress::new(array)) } } impl std::convert::TryFrom<&'_ str> for MacAddress { type Error = MacParseError; fn try_from(value: &str) -> Result { value.parse() } } impl std::convert::TryFrom> for MacAddress { type Error = MacParseError; fn try_from(value: std::borrow::Cow<'_, str>) -> Result { value.parse() } } 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(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn parse_str_colon() { let string = "80:FA:5B:41:10:6B"; let address = string.parse::().unwrap(); assert_eq!(address.bytes(), [128, 250, 91, 65, 16, 107]); assert_eq!(&format!("{}", address), string); } #[test] fn parse_str_hyphen() { let string = "01-23-45-67-89-AB"; let address = string.parse::().unwrap(); assert_eq!(address.bytes(), [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB]); assert_eq!(format!("{}", address), string.replace('-', ":")); } #[test] fn parse_invalid_length() { let string = "80:FA:5B:41:10:6B:AC"; let address = string.parse::().unwrap_err(); assert_eq!(MacParseError::InvalidLength, address); let string = "80:FA:5B:41"; let address = string.parse::().unwrap_err(); assert_eq!(MacParseError::InvalidLength, address); } #[test] fn parse_invalid_digit() { let string = "80:FA:ZZ:41:10:6B:AC"; let address = string.parse::().unwrap_err(); assert_eq!(MacParseError::InvalidDigit, address); } #[cfg(feature = "serde")] #[test] fn serde_works() { use serde::{Deserialize, Serialize}; use serde_test::{assert_tokens, Token}; let mac: MacAddress = "80:FA:5B:41:10:6B".parse().unwrap(); assert_tokens(&mac, &[Token::BorrowedStr("80:FA:5B:41:10:6B")]); #[derive(Serialize, Deserialize)] struct Test { mac: MacAddress, } assert_eq!( serde_json::to_string(&Test { mac }).unwrap(), serde_json::to_string::( &serde_json::from_str("{ \"mac\": \"80:FA:5B:41:10:6B\" }").unwrap() ) .unwrap(), ); } #[cfg(feature = "serde")] #[test] fn serde_from_reader_works() { use serde::{Deserialize, Serialize}; let mac: MacAddress = "80:FA:5B:41:10:6B".parse().unwrap(); #[derive(Serialize, Deserialize, PartialEq, Debug)] struct Test { mac: MacAddress, } assert_eq!( Test { mac }, serde_json::from_reader(std::io::Cursor::new(r#"{ "mac": "80:FA:5B:41:10:6B" }"#)) .unwrap(), ); } #[test] fn convert() { for mac in MacAddressIterator::new().unwrap() { let name = name_by_mac_address(&mac).unwrap().unwrap(); let mac2 = mac_address_by_name(&name).unwrap().unwrap(); assert_eq!(mac, mac2); } } } mac_address-1.1.5/src/linux.rs000064400000000000000000000023070072674642500144230ustar 00000000000000#![allow(dead_code)] use crate::MacAddressError; use nix::{ifaddrs::*, sys::socket::SockAddr}; /// Uses the `getifaddrs` call to retrieve a list of network interfaces on the /// host device and returns the first MAC address listed that isn't /// local-loopback or if a name was specified, that name. pub fn get_mac(name: Option<&str>) -> Result, MacAddressError> { let ifiter = getifaddrs()?; for interface in ifiter { if let Some(SockAddr::Link(link)) = interface.address { let bytes = link.addr(); if let Some(name) = name { if interface.interface_name == name { return Ok(Some(bytes)); } } else if bytes.iter().any(|&x| x != 0) { return Ok(Some(bytes)); } } } Ok(None) } pub fn get_ifname(mac: &[u8; 6]) -> Result, MacAddressError> { let ifiter = getifaddrs()?; for interface in ifiter { if let Some(SockAddr::Link(link)) = interface.address { let bytes = link.addr(); if &bytes == mac { return Ok(Some(interface.interface_name)); } } } Ok(None) } mac_address-1.1.5/src/windows.rs000064400000000000000000000144160072674642500147620ustar 00000000000000use core::convert::TryInto; use std::{convert::TryFrom, ffi::OsString, os::windows::ffi::OsStringExt, ptr, slice}; use winapi::shared::{ntdef::ULONG, winerror::ERROR_SUCCESS, ws2def::AF_UNSPEC}; use winapi::um::{iphlpapi::GetAdaptersAddresses, iptypes::IP_ADAPTER_ADDRESSES_LH}; use crate::MacAddressError; const GAA_FLAG_NONE: ULONG = 0x0000; /// Uses bindings to the `Iphlpapi.h` Windows header to fetch the interface /// devices list with /// [GetAdaptersAddresses][https://msdn.microsoft.com/en-us/library/windows/desktop/aa365915(v=vs.85).aspx] /// then loops over the returned list until it finds a network device with a MAC /// address, and returns it. /// /// If it fails to find a device, it returns a `NoDevicesFound` error. pub fn get_mac(name: Option<&str>) -> Result, MacAddressError> { let adapters = get_adapters()?; // Safety: We don't use the pointer after `adapters` is dropped let mut ptr = unsafe { adapters.ptr() }; loop { // Break if we've gone through all devices if ptr.is_null() { break; } let bytes = unsafe { convert_mac_bytes(ptr) }; if let Some(name) = name { #[cfg(not(target_pointer_width = "32"))] let adapter_name = unsafe { construct_string((*ptr).FriendlyName) }; #[cfg(target_pointer_width = "32")] let adapter_name = unsafe { construct_string(ptr.read_unaligned().FriendlyName) }; if adapter_name == name { return Ok(Some(bytes)); } } else if bytes.iter().any(|&x| x != 0) { return Ok(Some(bytes)); } // Otherwise go to the next device #[cfg(target_pointer_width = "32")] { ptr = unsafe { ptr.read_unaligned().Next }; } #[cfg(not(target_pointer_width = "32"))] { ptr = unsafe { (*ptr).Next }; } } Ok(None) } pub fn get_ifname(mac: &[u8; 6]) -> Result, MacAddressError> { let adapters = get_adapters()?; // Safety: We don't use the pointer after `adapters` is dropped let mut ptr = unsafe { adapters.ptr() }; loop { // Break if we've gone through all devices if ptr.is_null() { break; } let bytes = unsafe { convert_mac_bytes(ptr) }; if &bytes == mac { #[cfg(not(target_pointer_width = "32"))] let adapter_name = unsafe { construct_string((*ptr).FriendlyName) }; #[cfg(target_pointer_width = "32")] let adapter_name = unsafe { construct_string(ptr.read_unaligned().FriendlyName) }; let adapter_name = adapter_name .into_string() .map_err(|_| MacAddressError::InternalError)?; return Ok(Some(adapter_name)); } // Otherwise go to the next device #[cfg(target_pointer_width = "32")] { ptr = unsafe { ptr.read_unaligned().Next }; } #[cfg(not(target_pointer_width = "32"))] { ptr = unsafe { (*ptr).Next }; } } Ok(None) } /// Copy over the 6 MAC address bytes to the buffer. pub(crate) unsafe fn convert_mac_bytes(ptr: *mut IP_ADAPTER_ADDRESSES_LH) -> [u8; 6] { #[cfg(target_pointer_width = "32")] return ptr.read_unaligned().PhysicalAddress[..6] .try_into() .unwrap(); #[cfg(not(target_pointer_width = "32"))] return ((*ptr).PhysicalAddress)[..6].try_into().unwrap(); } pub(crate) struct AdaptersList { ptr: *mut IP_ADAPTER_ADDRESSES_LH, size: usize, } impl AdaptersList { /// Safety: The pointer returned by this method MUST NOT be used after /// `self` has gone out of scope. This pointer may also be null. pub(crate) unsafe fn ptr(&self) -> *mut IP_ADAPTER_ADDRESSES_LH { self.ptr } } impl Drop for AdaptersList { fn drop(&mut self) { if !self.ptr.is_null() && self.size != 0 { unsafe { std::alloc::dealloc( self.ptr as *mut u8, std::alloc::Layout::from_size_align( self.size, core::mem::align_of::(), ) .unwrap(), ) }; } } } pub(crate) fn get_adapters() -> Result { let mut buf_len = 0; // This will get the number of bytes we need to allocate for all devices unsafe { GetAdaptersAddresses( AF_UNSPEC as u32, GAA_FLAG_NONE, ptr::null_mut(), ptr::null_mut(), &mut buf_len, ); } if buf_len == 0 { return Ok(AdaptersList { ptr: ptr::null_mut(), size: 0, }); } // Allocate `buf_len` bytes, and create a raw pointer to it with the correct alignment // Safety: let adapters_list: *mut IP_ADAPTER_ADDRESSES_LH = unsafe { std::alloc::alloc( std::alloc::Layout::from_size_align( usize::try_from(buf_len).map_err(|_| MacAddressError::InternalError)?, core::mem::align_of::(), ) .unwrap(), ) } as *mut IP_ADAPTER_ADDRESSES_LH; // Get our list of adapters let result = unsafe { GetAdaptersAddresses( // [IN] Family AF_UNSPEC as u32, // [IN] Flags GAA_FLAG_NONE, // [IN] Reserved ptr::null_mut(), // [INOUT] AdapterAddresses adapters_list, // [INOUT] SizePointer &mut buf_len, ) }; let adapters_list = AdaptersList { ptr: adapters_list, // Cast OK, we checked it above size: buf_len as usize, }; // Make sure we were successful if result != ERROR_SUCCESS { return Err(MacAddressError::InternalError); } Ok(adapters_list) } unsafe fn construct_string(ptr: *mut u16) -> OsString { let slice = slice::from_raw_parts(ptr, get_null_position(ptr)); OsStringExt::from_wide(slice) } unsafe fn get_null_position(ptr: *mut u16) -> usize { assert!(!ptr.is_null()); for i in 0.. { if *ptr.offset(i) == 0 { return i as usize; } } unreachable!() }