### Create a Scraped Example in Rust Source: https://docs.rs/getifaddrs/latest/scrape-examples-help.html Shows how to create an example that calls a documented item from another crate. This example will be scraped and included in the documentation. ```rust // examples/ex.rs fn main() { a_crate::a_func(); } ``` -------------------------------- ### Example: Watching for Interface Changes Source: https://docs.rs/getifaddrs/latest/getifaddrs/fn.getifaddrs.html This example demonstrates how to use `getifaddrs` in a loop to detect and print changes in network interfaces. ```APIDOC ## Example: Watching for Interface Changes ```rust use getifaddrs::getifaddrs; use getifaddrs::Interface; fn main() { let mut last: Vec = Vec::default(); loop { let interfaces = getifaddrs().unwrap().collect::>(); if interfaces != last { println!("Interfaces changed:"); for interface in &interfaces { println!(" {:?}", interface); } last = interfaces; } } } ``` ``` -------------------------------- ### Example: Displaying Interface Information Source: https://docs.rs/getifaddrs/latest/getifaddrs/fn.getifaddrs.html This example shows how to retrieve and display detailed information about each network interface, including addresses, flags, and MAC addresses. ```APIDOC ## Example: Displaying Interface Information ```rust use getifaddrs::{getifaddrs, Address, Interfaces}; fn main() { let interfaces = getifaddrs().unwrap().collect::(); for (index, interface) in interfaces { println!("{}", interface.name); println!(" Flags: {:?}", interface.flags); #[cfg(windows)] println!(" Description: {:?}", interface.description); for address in interface.address.iter().flatten() { match address { Address::V4(..) | Address::V6(..) => { println!( " IP{:?}: {:?}", address.family(), address.ip_addr().unwrap() ); if let Some(netmask) = address.netmask() { println!(" Netmask: {}", netmask); } if let Some(associated_address) = address.associated_address() { println!(" Associated: {}", associated_address); } } Address::Mac(addr) => { println!( " Ether: {}", addr.iter() .map(|b| format!("{:02x}", b)) .collect::>() .join(":") ); } } } println!(" Index: {}", index); println!(); } } ``` ``` -------------------------------- ### Example: Ifconfig - Network Interface Information Source: https://docs.rs/getifaddrs/latest/getifaddrs/struct.Addresses.html This example demonstrates how to retrieve and display network interface information, including names, flags, IP addresses, netmasks, associated addresses, MAC addresses, and interface indices. It iterates through collected interfaces and their addresses. ```rust 3fn main() { let interfaces = getifaddrs().unwrap().collect::(); for (index, interface) in interfaces { println!("{}", interface.name); println!(" Flags: {:?}", interface.flags); #[cfg(windows)] println!(" Description: {:?}", interface.description); for address in interface.address.iter().flatten() { match address { Address::V4(..) | Address::V6(..) => { println!( " IP{:?}: {:?}", address.family(), address.ip_addr().unwrap() ); if let Some(netmask) = address.netmask() { println!(" Netmask: {}", netmask); } if let Some(associated_address) = address.associated_address() { println!(" Associated: {}", associated_address); } } Address::Mac(addr) => { println!( " Ether: {}", addr.iter() .map(|b| format!("{:02x}", b)) .collect::>() .join(":") ); } } } println!(" Index: {}", index); println!(); } } ``` -------------------------------- ### Filtering Network Interfaces with InterfaceFilter Source: https://docs.rs/getifaddrs/latest/src/getifaddrs/lib.rs.html Demonstrates how to use InterfaceFilter to retrieve specific network interfaces. Examples include getting all IPv4 interfaces, all IPv6 interfaces, and loopback interfaces. Note that filtering for both IPv4 and MAC addresses requires collecting results and then filtering further. ```rust # use std::io; # use getifaddrs::{InterfaceFilter, AddressFamily, Interfaces}; # fn main() -> io::Result<()> { # // Get all IPv4 interfaces let v4_interfaces = InterfaceFilter::new().v4().get()?; // Get all IPv6 interfaces let v6_interfaces = InterfaceFilter::new().v6().get()?; // Get all IPv4 interfaces with a MAC address. Note that you need // to collect v4 and mac addresses, then filter for interfaces with both. let v4_mac_interfaces = InterfaceFilter::new().v4().mac().get()?collect::() .iter().filter(|(_, interface)| interface.address.has(AddressFamily::Mac) && interface.address.has(AddressFamily::V4)); // Get loopback interfaces let loopback_interfaces = InterfaceFilter::new().loopback().get()?; # Ok(()) # } ``` -------------------------------- ### InterfaceFilter Examples Source: https://docs.rs/getifaddrs/latest/getifaddrs/struct.InterfaceFilter.html Illustrative examples demonstrating how to use the InterfaceFilter struct to retrieve specific network interfaces. ```APIDOC ## Examples ```rust // Get all IPv4 interfaces let v4_interfaces = InterfaceFilter::new().v4().get()?; // Get all IPv6 interfaces let v6_interfaces = InterfaceFilter::new().v6().get()?; // Get all IPv4 interfaces with a MAC address. Note that you need // to collect v4 and mac addresses, then filter for interfaces with both. let v4_mac_interfaces = InterfaceFilter::new().v4().mac().get()?.collect::() .iter().filter(|(_, interface)| interface.address.has(AddressFamily::Mac) && interface.address.has(AddressFamily::V4)); // Get loopback interfaces let loopback_interfaces = InterfaceFilter::new().loopback().get()?; ``` ``` -------------------------------- ### Example: Collecting and Iterating Interfaces Source: https://docs.rs/getifaddrs/latest/src/getifaddrs/lib.rs.html Demonstrates how to retrieve all network interfaces, collect them into an `Interfaces` BTreeMap, and then iterate over them to print details. ```rust # use getifaddrs::{getifaddrs, Interfaces}; let interfaces = getifaddrs().unwrap().collect::(); for (index, interface) in interfaces { eprintln!("Interface {index}: {interface:#?}"); } ``` -------------------------------- ### Collect and print interface details Source: https://docs.rs/getifaddrs/latest/getifaddrs/index.html This example shows how to collect all network interfaces into a map and then iterate through them to print detailed information, similar to the `ifconfig` command. ```APIDOC ## getifaddrs().collect::() ### Description Collects all network interfaces into a map where the key is the interface index and the value is the interface details. This is useful for structured access and comparison. ### Usage ```rust use getifaddrs::{getifaddrs, Address, Interfaces}; let interfaces = getifaddrs().unwrap().collect::(); for (index, interface) in interfaces { println!("{}", interface.name); println!(" Flags: {:?}", interface.flags); for address in interface.address.iter().flatten() { match address { Address::V4(..) | Address::V6(..) => { println!(" IP{:?}: {:?}", address.family(), address.ip_addr().unwrap()); if let Some(netmask) = address.netmask() { println!(" Netmask: {}", netmask); } #[cfg(not(windows))] if let Some(associated_address) = address.associated_address() { println!(" Associated: {}", associated_address); } } Address::Mac(addr) => { println!( " Ether: {}", addr.iter().map(|b| format!("{:02x}", b)).collect::>().join(":") ); } } } println!(" Index: {}", index); println!(); } ``` ``` -------------------------------- ### Collect and print interface details similar to ifconfig Source: https://docs.rs/getifaddrs/latest/index.html This example shows how to collect all network interfaces into a map and then print their details in a format resembling the `ifconfig` command. ```APIDOC ## getifaddrs().collect::() ### Description Collects all network interfaces into a map where keys are interface indices and values are interface details. This is useful for structured access and processing of interface information. ### Usage ```rust use getifaddrs::{getifaddrs, Address, Interfaces}; let interfaces = getifaddrs().unwrap().collect::(); for (index, interface) in interfaces { println!("{}", interface.name); println!(" Flags: {:?}", interface.flags); for address in interface.address.iter().flatten() { match address { Address::V4(..) | Address::V6(..) => { println!(" IP{:?}: {:?}", address.family(), address.ip_addr().unwrap()); if let Some(netmask) = address.netmask() { println!(" Netmask: {}", netmask); } #[cfg(not(windows))] if let Some(associated_address) = address.associated_address() { println!(" Associated: {}", associated_address); } } Address::Mac(addr) => { println!( " Ether: {}", addr.iter().map(|b| format!("{:02x}", b)).collect::>().join(":") ); } } } println!(" Index: {}", index); println!(); } ``` ``` -------------------------------- ### Iterate over all network interfaces Source: https://docs.rs/getifaddrs/latest/index.html This example demonstrates how to iterate over all network interfaces on the system and print details such as IP address, MAC address, netmask, and flags. ```APIDOC ## getifaddrs() ### Description Returns an iterator for all network interfaces on the system. ### Usage ```rust use getifaddrs::{getifaddrs, InterfaceFlags}; fn main() -> std::io::Result<()> { for interface in getifaddrs()? { println!("Interface: {}", interface.name); if let Some(ip_addr) = interface.address.ip_addr() { println!(" IP Address: {}", ip_addr); } if let Some(mac_addr) = interface.address.mac_addr() { println!(" MAC Address: {:?}", mac_addr); } if let Some(netmask) = interface.address.netmask() { println!(" Netmask: {}", netmask); } if let Some(associated_address) = interface.address.associated_address() { println!(" Associated Address: {}", associated_address); } println!(" Flags: {:?}", interface.flags); if interface.flags.contains(InterfaceFlags::UP) { println!(" Status: Up"); } else { println!(" Status: Down"); } println!(); } Ok(()) } ``` ``` -------------------------------- ### Collect and Display Network Interface Details Source: https://docs.rs/getifaddrs This example collects all network interfaces into an `Interfaces` map and then iterates through them to display details similar to the `ifconfig` command. It handles IPv4, IPv6, and MAC addresses, and includes interface index. Note the conditional compilation for associated addresses on non-Windows systems. ```rust use getifaddrs::{getifaddrs, Address, Interfaces}; let interfaces = getifaddrs().unwrap().collect::(); for (index, interface) in interfaces { println!("{}", interface.name); println!(" Flags: {:?}", interface.flags); for address in interface.address.iter().flatten() { match address { Address::V4(..) | Address::V6(..) => { println!(" IP{:?}: {:?}", address.family(), address.ip_addr().unwrap()); if let Some(netmask) = address.netmask() { println!(" Netmask: {}", netmask); } #[cfg(not(windows))] if let Some(associated_address) = address.associated_address() { println!(" Associated: {}", associated_address); } } Address::Mac(addr) => { println!( " Ether: {}", addr.iter().map(|b| format!("{:02x}", b)).collect::>().join(":") ); } } } println!(" Index: {}", index); println!(); } ``` -------------------------------- ### Iterate over all network interfaces Source: https://docs.rs/getifaddrs/latest/getifaddrs/index.html This example demonstrates how to iterate over all network interfaces on the system and print basic information about each, including its name, IP address, MAC address, netmask, and flags. ```APIDOC ## getifaddrs() ### Description Returns an iterator for all network interfaces on the system. ### Function Signature `getifaddrs() -> Result, std::io::Error>` ### Usage ```rust use getifaddrs::{getifaddrs, InterfaceFlags}; fn main() -> std::io::Result<()> { for interface in getifaddrs()? { println!("Interface: {}", interface.name); if let Some(ip_addr) = interface.address.ip_addr() { println!(" IP Address: {}", ip_addr); } if let Some(mac_addr) = interface.address.mac_addr() { println!(" MAC Address: {:?}", mac_addr); } if let Some(netmask) = interface.address.netmask() { println!(" Netmask: {}", netmask); } if let Some(associated_address) = interface.address.associated_address() { println!(" Associated Address: {}", associated_address); } println!(" Flags: {:?}", interface.flags); if interface.flags.contains(InterfaceFlags::UP) { println!(" Status: Up"); } else { println!(" Status: Down"); } println!(); } Ok(()) } ``` ``` -------------------------------- ### Collect and Print Network Interface Details Source: https://docs.rs/getifaddrs/latest/getifaddrs/index.html This example collects all network interfaces into an `Interfaces` map and then iterates through them to print details similar to the `ifconfig` command. It handles IPv4, IPv6, and MAC addresses, and includes conditional logic for associated addresses on non-Windows systems. Requires imports for `getifaddrs`, `Address`, and `Interfaces`. ```rust use getifaddrs::{getifaddrs, Address, Interfaces}; let interfaces = getifaddrs().unwrap().collect::(); for (index, interface) in interfaces { println!("{}", interface.name); println!(" Flags: {:?}", interface.flags); for address in interface.address.iter().flatten() { match address { Address::V4(..) | Address::V6(..) => { println!(" IP{:?}: {:?}", address.family(), address.ip_addr().unwrap()); if let Some(netmask) = address.netmask() { println!(" Netmask: {}", netmask); } #[cfg(not(windows))] if let Some(associated_address) = address.associated_address() { println!(" Associated: {}", associated_address); } } Address::Mac(addr) => { println!( " Ether: {}", addr.iter().map(|b| format!("{:02x}", b)).collect::>().join(":") ); } } } println!(" Index: {}", index); println!(); } ``` -------------------------------- ### Collect and display interface information Source: https://docs.rs/getifaddrs This example collects all network interfaces and prints their details in a format similar to the `ifconfig` command, handling different address types (IPv4, IPv6, MAC). ```APIDOC ## Example: Collect and display interface information ### Description This snippet demonstrates collecting all network interfaces into a `Interfaces` map and then iterating through them to display details like flags, IP addresses, netmasks, and MAC addresses, mimicking the output of the `ifconfig` command. ### Usage ```rust use getifaddrs::{getifaddrs, Address, Interfaces}; let interfaces = getifaddrs().unwrap().collect::(); for (index, interface) in interfaces { println!("{}", interface.name); println!(" Flags: {:?}", interface.flags); for address in interface.address.iter().flatten() { match address { Address::V4(..) | Address::V6(..) => { println!(" IP{:?}: {:?}", address.family(), address.ip_addr().unwrap()); if let Some(netmask) = address.netmask() { println!(" Netmask: {}", netmask); } #[cfg(not(windows))] if let Some(associated_address) = address.associated_address() { println!(" Associated: {}", associated_address); } } Address::Mac(addr) => { println!( " Ether: {}", addr.iter().map(|b| format!("{:02x}", b)).collect::>().join(":") ); } } } println!(" Index: {}", index); println!(); } ``` ``` -------------------------------- ### Iterate Over Network Interfaces Source: https://docs.rs/getifaddrs This example demonstrates how to iterate through all network interfaces on the system and print their basic information, including IP and MAC addresses, netmask, and flags. It requires the `getifaddrs` crate. ```rust use getifaddrs::{getifaddrs, InterfaceFlags}; fn main() -> std::io::Result<()> { for interface in getifaddrs()? { println!("Interface: {}", interface.name); if let Some(ip_addr) = interface.address.ip_addr() { println!(" IP Address: {}", ip_addr); } if let Some(mac_addr) = interface.address.mac_addr() { println!(" MAC Address: {:?}", mac_addr); } if let Some(netmask) = interface.address.netmask() { println!(" Netmask: {}", netmask); } if let Some(associated_address) = interface.address.associated_address() { println!(" Associated Address: {}", associated_address); } println!(" Flags: {:?}", interface.flags); if interface.flags.contains(InterfaceFlags::UP) { println!(" Status: Up"); } else { println!(" Status: Down"); } println!(); } Ok(()) } ``` -------------------------------- ### Create and Use InterfaceFilter Source: https://docs.rs/getifaddrs/latest/getifaddrs/struct.InterfaceFilter.html Demonstrates how to create an InterfaceFilter and apply common filtering methods like v4(), v6(), and mac(). The example also shows how to collect and filter interfaces that have both IPv4 and MAC addresses. ```rust // Get all IPv4 interfaces let v4_interfaces = InterfaceFilter::new().v4().get()?; // Get all IPv6 interfaces let v6_interfaces = InterfaceFilter::new().v6().get()?; // Get all IPv4 interfaces with a MAC address. Note that you need // to collect v4 and mac addresses, then filter for interfaces with both. let v4_mac_interfaces = InterfaceFilter::new().v4().mac().get()?.collect::() .iter().filter(|(_, interface)| interface.address.has(AddressFamily::Mac) && interface.address.has(AddressFamily::V4)); // Get loopback interfaces let loopback_interfaces = InterfaceFilter::new().loopback().get()?; ``` -------------------------------- ### Iterate Over All Network Interfaces Source: https://docs.rs/getifaddrs/latest/getifaddrs/index.html This example demonstrates how to iterate over all network interfaces on the system and print their name, IP address, MAC address, netmask, and flags. It requires the `getifaddrs` and `InterfaceFlags` imports. ```rust use getifaddrs::{getifaddrs, InterfaceFlags}; fn main() -> std::io::Result<()> { for interface in getifaddrs()? { println!("Interface: {}", interface.name); if let Some(ip_addr) = interface.address.ip_addr() { println!(" IP Address: {}", ip_addr); } if let Some(mac_addr) = interface.address.mac_addr() { println!(" MAC Address: {:?}", mac_addr); } if let Some(netmask) = interface.address.netmask() { println!(" Netmask: {}", netmask); } if let Some(associated_address) = interface.address.associated_address() { println!(" Associated Address: {}", associated_address); } println!(" Flags: {:?}", interface.flags); if interface.flags.contains(InterfaceFlags::UP) { println!(" Status: Up"); } else { println!(" Status: Down"); } println!(); } Ok(()) } ``` -------------------------------- ### InterfaceFilter::new Source: https://docs.rs/getifaddrs/latest/src/getifaddrs/lib.rs.html Creates a new `InterfaceFilter` with no criteria set. This is the starting point for building a filter. ```APIDOC ## InterfaceFilter::new ### Description Creates a new `InterfaceFilter` with no criteria set. ### Method `InterfaceFilter::new()` ### Returns A new `InterfaceFilter` instance. ``` -------------------------------- ### Iterate and Print Network Interface Information Source: https://docs.rs/getifaddrs/latest/getifaddrs/enum.Address.html This example demonstrates how to retrieve and iterate through network interfaces, printing details such as IP addresses, netmasks, and MAC addresses. It uses `getifaddrs` to fetch interface data and `match` statements to handle different `Address` variants. ```rust 3fn main() { 4 let interfaces = getifaddrs().unwrap().collect::(); 5 for (index, interface) in interfaces { 6 println!("{}", interface.name); 7 println!(" Flags: {:?}", interface.flags); 8 #[cfg(windows)] 9 println!(" Description: {:?}", interface.description); 10 for address in interface.address.iter().flatten() { 11 match address { 12 Address::V4(..) | Address::V6(..) => { 13 println!( 14 " IP{:?}: {:?}", 15 address.family(), 16 address.ip_addr().unwrap() 17 ); 18 if let Some(netmask) = address.netmask() { 19 println!(" Netmask: {}", netmask); 20 } 21 if let Some(associated_address) = address.associated_address() { 22 println!(" Associated: {}", associated_address); 23 } 24 } 25 Address::Mac(addr) => { 26 println!( 27 " Ether: {}", 28 addr.iter() 29 .map(|b| format!("{:02x}", b)) 30 .collect::>() 31 .join(":") 32 ); 33 } 34 } 35 } 36 println!(" Index: {}", index); 37 println!(); 38 } 39} ``` -------------------------------- ### get Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Retrieves a reference to the value corresponding to the given key. ```APIDOC ## get(&self, key: &Q) -> Option<&V> ### Description Returns a reference to the value corresponding to the key. ### Method `get` ### Parameters - `key` (&Q): The key to search for. The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type. ### Returns - `Option<&V>`: An `Option` containing a reference to the value if the key is found, otherwise `None`. ``` -------------------------------- ### Get BTreeMap Keys Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Shows how to retrieve an iterator over the keys of a `BTreeMap` in sorted order. This is useful when you only need to access the keys. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(2, "b"); a.insert(1, "a"); let keys: Vec<_> = a.keys().cloned().collect(); assert_eq!(keys, [1, 2]); ``` -------------------------------- ### Create a new InterfaceFilter Source: https://docs.rs/getifaddrs/latest/getifaddrs/struct.InterfaceFilter.html Initializes a new InterfaceFilter with no specific criteria set. This is the starting point for building a custom interface filter. ```rust pub fn new() -> Self ``` -------------------------------- ### Creating a New InterfaceFilter Source: https://docs.rs/getifaddrs/latest/src/getifaddrs/lib.rs.html Initializes a new InterfaceFilter with default settings, meaning no specific criteria are applied initially. This is the starting point for building a filter chain. ```rust let mut filter = InterfaceFilter::new(); ``` -------------------------------- ### get Source: https://docs.rs/getifaddrs/latest/getifaddrs/struct.Addresses.html Retrieves the first address associated with a given address family from the collection. ```APIDOC ## get ### Description Returns the first address associated with the given address family. ### Method `get(&self, family: AddressFamily) -> Option<&Address>` ### Parameters - **family** (`AddressFamily`) - The address family to search for. ### Returns - `Option<&Address>` - An optional reference to the `Address` if found, otherwise `None`. ``` -------------------------------- ### Get and Display Network Interface Information Source: https://docs.rs/getifaddrs/latest/src/ifconfig/ifconfig.rs.html This snippet retrieves all network interfaces and iterates through them, printing details such as name, flags, IP addresses (IPv4 and IPv6), netmasks, associated addresses, and MAC addresses. It includes platform-specific handling for Windows descriptions. Use this to inspect network configuration. ```rust use getifaddrs::{getifaddrs, Address, Interfaces}; fn main() { let interfaces = getifaddrs().unwrap().collect::(); for (index, interface) in interfaces { println!("{}", interface.name); println!(" Flags: {:?}", interface.flags); #[cfg(windows)] println!(" Description: {:?}", interface.description); for address in interface.address.iter().flatten() { match address { Address::V4(..) | Address::V6(..) => { println!( " IP{:?}: {:?}", address.family(), address.ip_addr().unwrap() ); if let Some(netmask) = address.netmask() { println!(" Netmask: {}", netmask); } if let Some(associated_address) = address.associated_address() { println!(" Associated: {}", associated_address); } } Address::Mac(addr) => { println!( " Ether: {}", addr.iter() .map(|b| format!("{:02x}", b)) .collect::>() .join(":") ); } } } println!(" Index: {}", index); println!(); } } ``` -------------------------------- ### Get IP Address Source: https://docs.rs/getifaddrs/latest/getifaddrs/enum.Address.html Returns the IP address of the address, if this is an IPv4 or IPv6 address. Returns `None` for MAC addresses. ```rust pub fn ip_addr(&self) -> Option ``` -------------------------------- ### Get All Network Interfaces Source: https://docs.rs/getifaddrs/latest/src/getifaddrs/lib.rs.html Retrieves an iterator for all network interfaces on the system. This is equivalent to calling `InterfaceFilter::new().get()`. The output can be collected into a `BTreeMap` for easier access. ```rust pub fn getifaddrs() -> std::io::Result> { InterfaceFilter::new().get() } ``` -------------------------------- ### Monitor Network Interface Changes Source: https://docs.rs/getifaddrs/latest/getifaddrs/fn.getifaddrs.html Continuously monitors network interfaces for changes, printing updated information when modifications are detected. This example uses a loop to compare the current interface list with the previous one. ```rust pub fn main() { let mut last: Vec = Vec::default(); loop { let interfaces = getifaddrs().unwrap().collect::>(); if interfaces != last { println!("Interfaces changed:"); for interface in &interfaces { println!(" {interface:?}"); } last = interfaces; } } } ``` -------------------------------- ### Include a Public Function in Rustdoc Source: https://docs.rs/getifaddrs/latest/scrape-examples-help.html Demonstrates how a public function in a crate's source code can be documented. This function serves as a target for scraped examples. ```rust // src/lib.rs pub fn a_func() {} ``` -------------------------------- ### Get MAC Address Source: https://docs.rs/getifaddrs/latest/getifaddrs/enum.Address.html Returns the MAC address of the address, if this is a MAC address. Returns `None` otherwise. ```rust pub fn mac_addr(&self) -> Option<[u8; 6]> ``` -------------------------------- ### Get BTreeMap Length Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Demonstrates how to get the number of elements currently stored in a `BTreeMap`. This is useful for checking the size of the map. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); assert_eq!(a.len(), 0); a.insert(1, "a"); assert_eq!(a.len(), 1); ``` -------------------------------- ### Get BTreeMap Values Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Demonstrates how to get an iterator over the values of a `BTreeMap`, ordered according to their corresponding keys. Useful for accessing only the values. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, "hello"); a.insert(2, "goodbye"); let values: Vec<&str> = a.values().cloned().collect(); assert_eq!(values, ["hello", "goodbye"]); ``` -------------------------------- ### Get Number of Address Families Source: https://docs.rs/getifaddrs/latest/getifaddrs/struct.Addresses.html Returns the count of distinct address families present in the collection. To get the total number of individual addresses, you need to iterate and sum the lengths of the address slices. ```rust pub fn len(&self) -> usize ``` -------------------------------- ### Iterate Over a Sub-Range of BTreeMap Elements Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Constructs a double-ended iterator over a sub-range of elements. Supports various range syntaxes and bound combinations. Panics if range start exceeds end or if start equals end with excluded bounds. ```rust use std::collections::BTreeMap; use std::ops::Bound::Included; let mut map = BTreeMap::new(); map.insert(3, "a"); map.insert(5, "b"); map.insert(8, "c"); for (&key, &value) in map.range((Included(&4), Included(&8))) { println!("{key}: {value}"); } assert_eq!(Some((&5, &"b")), map.range(4..).next()); ``` -------------------------------- ### get_key_value Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Retrieves a reference to the key-value pair corresponding to the supplied key. This is useful for key types where non-identical keys can be considered equal, for getting the stored key from a borrowed lookup key, or for getting a reference to a key with the same lifetime as the collection. ```APIDOC ## get_key_value(&self, k: &Q) -> Option<(&K, &V)> ### Description Returns the key-value pair corresponding to the supplied key. This is potentially useful: * for key types where non-identical keys can be considered equal; * for getting the `&K` stored key value from a borrowed `&Q` lookup key; or * for getting a reference to a key with the same lifetime as the collection. The supplied key may be any borrowed form of the map’s key type, but the ordering on the borrowed form _must_ match the ordering on the key type. ### Parameters #### Path Parameters - `k` (*Q): The key to search for. ### Response #### Success Response (200) - `Option<(&K, &V)>`: An Option containing a tuple of references to the key and value if found, otherwise None. ### Request Example ```rust use std::cmp::Ordering; use std::collections::BTreeMap; #[derive(Clone, Copy, Debug)] struct S { id: u32, name: &'static str, // ignored by equality and ordering operations } impl PartialEq for S { fn eq(&self, other: &S) -> bool { self.id == other.id } } impl Eq for S {} impl PartialOrd for S { fn partial_cmp(&self, other: &S) -> Option { self.id.partial_cmp(&other.id) } } impl Ord for S { fn cmp(&self, other: &S) -> Ordering { self.id.cmp(&other.id) } } let j_a = S { id: 1, name: "Jessica" }; let j_b = S { id: 1, name: "Jess" }; let p = S { id: 2, name: "Paul" }; assert_eq!(j_a, j_b); let mut map = BTreeMap::new(); map.insert(j_a, "Paris"); assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris"))); assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case assert_eq!(map.get_key_value(&p), None); ``` ``` -------------------------------- ### Get immutable cursor after greatest key <= bound Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Use `upper_bound` to get an immutable cursor positioned after the greatest key that is less than or equal to the specified bound. This is useful for iterating or inspecting elements relative to a key without modification. ```rust #![feature(btree_cursors)] use std::collections::BTreeMap; use std::ops::Bound; let map = BTreeMap::from([ (1, "a"), (2, "b"), (3, "c"), (4, "d"), ]); let cursor = map.upper_bound(Bound::Included(&3)); assert_eq!(cursor.peek_prev(), Some((&3, &"c"))); assert_eq!(cursor.peek_next(), Some((&4, &"d"))); let cursor = map.upper_bound(Bound::Excluded(&3)); assert_eq!(cursor.peek_prev(), Some((&2, &"b"))); assert_eq!(cursor.peek_next(), Some((&3, &"c"))); let cursor = map.upper_bound(Bound::Unbounded); assert_eq!(cursor.peek_prev(), Some((&4, &"d"))); assert_eq!(cursor.peek_next(), None); ``` -------------------------------- ### Mutable Iteration Over a Sub-Range of BTreeMap Elements Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Constructs a mutable double-ended iterator over a sub-range. Supports various range syntaxes and bound combinations. Panics if range start exceeds end or if start equals end with excluded bounds. ```rust use std::collections::BTreeMap; let mut map: BTreeMap<&str, i32> = [("Alice", 0), ("Bob", 0), ("Carol", 0), ("Cheryl", 0)].into(); for (_, balance) in map.range_mut("B".."Cheryl") { *balance += 100; } for (name, balance) in &map { println!("{name} => {balance}"); } ``` -------------------------------- ### Get TypeId Source: https://docs.rs/getifaddrs/latest/getifaddrs/struct.InterfaceFilter.html Retrieves the `TypeId` of the `InterfaceFilter` struct, useful for runtime type information. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Get Netmask Source: https://docs.rs/getifaddrs/latest/getifaddrs/enum.Address.html Returns the netmask of the address, if this is an IPv4 or IPv6 address. Returns `None` for MAC addresses. ```rust pub fn netmask(&self) -> Option ``` -------------------------------- ### Basic BTreeMap Usage Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Demonstrates basic insertion and retrieval of key-value pairs in a BTreeMap. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### new_in Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Creates a new empty BTreeMap with a specified allocator. This is a nightly-only experimental API. ```APIDOC ## new_in(alloc: A) -> BTreeMap ### Description Makes a new empty BTreeMap with a specified allocator. ### Method `new_in` ### Parameters - `alloc` (A): The allocator to use for the BTreeMap. ### Returns - `BTreeMap`: A new, empty BTreeMap. ### Remarks This is a nightly-only experimental API. (`btreemap_alloc`) ``` -------------------------------- ### Create a default BTreeMap Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Implement `Default` to create an empty `BTreeMap`. ```rust fn default() -> BTreeMap ``` -------------------------------- ### Display Network Interface Details Source: https://docs.rs/getifaddrs/latest/getifaddrs/fn.getifaddrs.html Iterates through all network interfaces and prints detailed information for each, including name, flags, description (on Windows), IP addresses (IPv4/IPv6), netmasks, associated addresses, MAC addresses, and index. This is useful for a comprehensive overview of network configuration. ```rust fn main() { let interfaces = getifaddrs().unwrap().collect::(); for (index, interface) in interfaces { println!("{}", interface.name); println!(" Flags: {:?}", interface.flags); #[cfg(windows)] println!(" Description: {:?}", interface.description); for address in interface.address.iter().flatten() { match address { Address::V4(..) | Address::V6(..) => { println!( " IP{:?}: {:?}", address.family(), address.ip_addr().unwrap() ); if let Some(netmask) = address.netmask() { println!(" Netmask: {}", netmask); } if let Some(associated_address) = address.associated_address() { println!(" Associated: {}", associated_address); } } Address::Mac(addr) => { println!( " Ether: {}", addr.iter() .map(|b| format!("{:02x}", b)) .collect::>() .join(":") ); } } } println!(" Index: {}", index); println!(); } } ``` -------------------------------- ### Collect Network Interfaces Source: https://docs.rs/getifaddrs/latest/getifaddrs/fn.getifaddrs.html Demonstrates collecting all network interfaces into a `Interfaces` collection (a `BTreeMap`) and iterating over them. Useful for inspecting interface details. ```rust let interfaces = getifaddrs().unwrap().collect::(); for (index, interface) in interfaces { eprintln!("Interface {index}: {interface:#?}"); } ``` -------------------------------- ### Get Address Family Source: https://docs.rs/getifaddrs/latest/getifaddrs/enum.Address.html Returns the address family of the address. This can be used to determine if an address is IPv4, IPv6, or another type. ```rust pub fn family(&self) -> AddressFamily ``` -------------------------------- ### PartialEq Implementation Source: https://docs.rs/getifaddrs/latest/getifaddrs/enum.Address.html Enables basic equality comparison for Address instances. ```APIDOC ## PartialEq ### Description Provides the equality comparison operator (`==`) for Address instances. ### Method `eq(&self, other: &Self) -> bool` ### Parameters - `other`: A reference to the other Address instance to compare. ### Response - `bool`: True if the two Address instances are equal, false otherwise. ``` -------------------------------- ### Get All Addresses by Family Source: https://docs.rs/getifaddrs/latest/getifaddrs/struct.Addresses.html Retrieves all addresses associated with a specific address family. Returns None if no addresses of that family are found. ```rust pub fn get_all(&self, family: AddressFamily) -> Option<&[Address]> ``` -------------------------------- ### Try Insert into BTreeMap (Nightly) Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Demonstrates the experimental `try_insert` method for inserting a key-value pair. It returns a mutable reference on success or an error if the key already exists, providing access to the occupied entry. ```rust #![feature(map_try_insert)] use std::collections::BTreeMap; let mut map = BTreeMap::new(); assert_eq!(map.try_insert(37, "a").unwrap(), &"a"); let err = map.try_insert(37, "b").unwrap_err(); assert_eq!(err.entry.key(), &37); assert_eq!(err.entry.get(), &"a"); assert_eq!(err.value, "b"); ``` -------------------------------- ### Get Last Key-Value Pair Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Retrieves the last key-value pair (maximum key) from the BTreeMap. Returns None if the map is empty. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1, "b"); map.insert(2, "a"); assert_eq!(map.last_key_value(), Some((&2, &"a"))); ``` -------------------------------- ### Create a New BTreeMap Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Illustrates creating an empty `BTreeMap` which can then be populated with key-value pairs. This is a fundamental operation for using map-like structures. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); // entries can now be inserted into the empty map map.insert(1, "a"); ``` -------------------------------- ### Get First Key-Value Pair Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Retrieves the first key-value pair (minimum key) from the BTreeMap. Returns None if the map is empty. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); assert_eq!(map.first_key_value(), None); map.insert(1, "b"); map.insert(2, "a"); assert_eq!(map.first_key_value(), Some((&1, &"b"))); ``` -------------------------------- ### BTreeMap Implementations Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Provides documentation for common `BTreeMap` methods that are relevant when working with the `Interfaces` type alias. ```APIDOC ## BTreeMap Methods ### `new()` Creates a new, empty `BTreeMap`. ### `iter()` Gets an iterator over the entries of the map, sorted by key. ### `iter_mut()` Gets a mutable iterator over the entries of the map, sorted by key. ### `keys()` Gets an iterator over the keys of the map, in sorted order. ### `values()` Gets an iterator over the values of the map, in order by key. ### `values_mut()` Gets a mutable iterator over the values of the map, in order by key. ### `len()` Returns the number of elements in the map. ### `is_empty()` Returns `true` if the map contains no elements. ### `lower_bound()` (Nightly-only) Returns a `Cursor` pointing at the gap before the smallest key greater than the given bound. ``` -------------------------------- ### Get First Address by Family Source: https://docs.rs/getifaddrs/latest/getifaddrs/struct.Addresses.html Retrieves the first address associated with a specific address family. Returns None if no address of that family is found. ```rust pub fn get(&self, family: AddressFamily) -> Option<&Address> ``` -------------------------------- ### take Source: https://docs.rs/getifaddrs/latest/getifaddrs/struct.AddressesIter.html Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ```APIDOC ## fn take(self, n: usize) -> Take ### Description Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ### Parameters * `n` (usize) - The maximum number of elements to yield. ``` -------------------------------- ### Nightly-only Experimental APIs Source: https://docs.rs/getifaddrs/latest/getifaddrs/struct.AddressesIter.html These methods are experimental and require a nightly Rust toolchain. ```APIDOC ### fn next_chunk( &mut self, ) -> Result<[Self::Item; N], IntoIter> Advances the iterator and returns an array containing the next `N` values. ### fn advance_by(&mut self, n: usize) -> Result<(), NonZero> Advances the iterator by `n` elements. ### fn intersperse(self, separator: Self::Item) -> Intersperse Creates a new iterator which places a copy of `separator` between items of the original iterator. ### fn intersperse_with(self, separator: G) -> IntersperseWith Creates a new iterator which places an item generated by `separator` between items of the original iterator. ``` -------------------------------- ### CloneToUninit Implementation for T Source: https://docs.rs/getifaddrs/latest/getifaddrs/struct.Interface.html An experimental nightly-only API that allows cloning a value into uninitialized memory. Use with caution as it is unsafe. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Return Interface Structure Source: https://docs.rs/getifaddrs/latest/src/getifaddrs/unix.rs.html Returns a completed Interface structure containing the name, address, flags, and index. ```rust return Some(Interface { name, address, flags, index, ``` -------------------------------- ### Convert interface name to index Source: https://docs.rs/getifaddrs/latest/getifaddrs/fn.if_nametoindex.html Use this function to get the numerical index of a network interface given its name. It handles potential errors during conversion. ```rust match getifaddrs::if_nametoindex("eth0") { Ok(index) => println!("Interface index: {}", index), Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Clone Implementation Source: https://docs.rs/getifaddrs/latest/getifaddrs/enum.Address.html Provides methods for cloning Address instances. ```APIDOC ## clone ### Description Returns a duplicate of the Address value. ### Method `clone(&self) -> Address` ### Parameters None ### Response - `Address`: A new Address instance that is a duplicate of the original. ## clone_from ### Description Performs copy-assignment from a source Address. ### Method `clone_from(&mut self, source: &Self)` ### Parameters - `source`: A reference to the Address to copy from. ### Response None ``` -------------------------------- ### Get Mutable BTreeMap Values Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Shows how to obtain a mutable iterator over the values of a `BTreeMap`, allowing in-place modification of values based on their sorted key order. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, String::from("hello")); a.insert(2, String::from("goodbye")); for value in a.values_mut() { value.push_str("!"); } let values: Vec = a.values().cloned().collect(); assert_eq!(values, [String::from("hello!"), String::from("goodbye!")]); ``` -------------------------------- ### Create new BTreeMap with allocator Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Use `new_in` to create an empty BTreeMap that uses a specific allocator. This is an experimental API and requires the `btreemap_alloc` feature. ```rust #![feature(btreemap_alloc)] use std::collections::BTreeMap; use std::alloc::Global; let mut map = BTreeMap::new_in(Global); // entries can now be inserted into the empty map map.insert(1, "a"); ``` -------------------------------- ### clone_to_uninit Source: https://docs.rs/getifaddrs/latest/getifaddrs/struct.InterfaceFlags.html Performs copy-assignment from `self` to `dest`. This is a nightly-only experimental API. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. ### Safety This function is unsafe because it operates on raw pointers and assumes `dest` is a valid, mutable pointer to a buffer large enough to hold the data. ### Notes This is a nightly-only experimental API. ``` -------------------------------- ### InterfaceFlags Iterators Source: https://docs.rs/getifaddrs/latest/getifaddrs/struct.InterfaceFlags.html Methods for iterating over the flags within an InterfaceFlags value. Use `iter` to get all flags including unknown bits, or `iter_names` for only named flags. ```rust pub const fn iter(&self) -> Iter ``` ```rust pub const fn iter_names(&self) -> IterNames ``` -------------------------------- ### Index<&Q> for BTreeMap Source: https://docs.rs/getifaddrs/latest/getifaddrs/type.Interfaces.html Allows indexing into the BTreeMap using a borrowed key. ```APIDOC ## fn index(&self, key: &Q) -> &V ### Description Returns a reference to the value corresponding to the supplied key. ### Panics Panics if the key is not present in the `BTreeMap`. ``` -------------------------------- ### Hash Implementation Source: https://docs.rs/getifaddrs/latest/getifaddrs/enum.Address.html Enables Address instances to be hashed. ```APIDOC ## hash ### Description Feeds the Address value into the given Hasher. ### Method `hash<__H: Hasher>(&self, state: &mut __H)` ### Parameters - `state`: A mutable reference to the Hasher. ### Response None ## hash_slice ### Description Feeds a slice of Address values into the given Hasher. ### Method `hash_slice(data: &[Self], state: &mut H) where H: Hasher, Self: Sized` ### Parameters - `data`: A slice of Address values. - `state`: A mutable reference to the Hasher. ### Response None ```