### List Network Interfaces Source: https://docs.rs/netwatcher/0.4.1/netwatcher/index.html This example demonstrates how to retrieve a HashMap of all currently enabled network interfaces and their associated IP addresses. ```APIDOC ## GET /api/interfaces ### Description Retrieves information about all enabled network interfaces and their IP addresses. ### Method GET ### Endpoint /api/interfaces ### Parameters None ### Request Example None ### Response #### Success Response (200) - **interfaces** (HashMap) - A map where keys are interface indexes (u32) and values are Interface structs containing interface details. #### Response Example ```json { "interfaces": { "1": { "name": "eth0", "ips": [ { "ip": "192.168.1.100", "prefix_len": 24 } ] }, "2": { "name": "lo", "ips": [ { "ip": "127.0.0.1", "prefix_len": 8 } ] } } } ``` ``` -------------------------------- ### Watch for Network Interface Changes Source: https://docs.rs/netwatcher/0.4.1/netwatcher/index.html This example shows how to set up a callback that is triggered immediately with the current interface state and subsequently whenever network interfaces change. It utilizes an efficient, platform-specific mechanism to detect changes. ```APIDOC ## POST /api/interfaces/watch ### Description Starts watching for changes to network interfaces. A callback function is invoked immediately with the current state and then again whenever an update occurs. This method uses efficient, platform-specific change detection. ### Method POST ### Endpoint /api/interfaces/watch ### Parameters #### Request Body - **callback** (function) - Required - A function that accepts an `Update` struct containing the latest interface snapshot and a diff of changes. ### Request Example ```json { "callback": "function(update) { console.log(update); }" } ``` ### Response #### Success Response (200) - **handle** (WatchHandle) - A handle that must be kept alive to continue receiving callbacks. Dropping this handle stops the watching process. #### Response Example ```json { "handle": "" } ``` ``` -------------------------------- ### Implement CloneToUninit for T (Nightly) Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Nightly-only experimental API for performing copy-assignment from self to a raw pointer destination. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### List Network Interfaces Source: https://docs.rs/netwatcher Retrieves a snapshot of all current network interfaces and their associated IP addresses. ```rust /// Returns a HashMap from ifindex (a `u32`) to an `Interface` struct let interfaces = netwatcher::list_interfaces().unwrap(); for i in interfaces.values() { println!("interface {}", i.name); for ip_record in &i.ips { println!("IP: {}/{}", ip_record.ip, ip_record.prefix_len); } } ``` -------------------------------- ### Implement Any for T Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Provides type information for any type T. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Retrieve Network Interface Information Source: https://docs.rs/netwatcher/0.4.1/netwatcher/fn.list_interfaces.html Fetches current information about all active network interfaces and their IP addresses. This is a single operation; for continuous monitoring, use `watch_interfaces`. ```rust pub fn list_interfaces() -> Result, Error> ``` -------------------------------- ### list_interfaces Source: https://docs.rs/netwatcher/0.4.1/netwatcher/fn.list_interfaces.html Retrieves information about all enabled network interfaces and their associated IP addresses. ```APIDOC ## GET /list_interfaces ### Description Retrieve information about all enabled network interfaces and their IP addresses. This is a once-off operation. ### Method GET ### Endpoint /list_interfaces ### Response #### Success Response (200) - **HashMap** - A map where the key is the interface index and the value is the Interface object containing details. ``` -------------------------------- ### Watch Network Interface Changes Source: https://docs.rs/netwatcher/0.4.1/netwatcher/fn.watch_interfaces.html Use this function to retrieve initial interface information and continuously watch for changes. The returned `WatchHandle` must be held to keep the watcher active. The callback receives an `Update` struct containing the current interface state and a diff of changes. ```rust pub fn watch_interfaces( callback: F, ) -> Result ``` ```rust fn main() { println!("Watching for changes for 30 seconds..."); let handle = netwatcher::watch_interfaces(|update| { println!("Interface update!"); println!("State: {:#?}", update.interfaces); println!("Diff: {:#?}", update.diff); }) .unwrap(); std::thread::sleep(Duration::from_secs(30)); drop(handle); println!("Stopped watching! Program will end in 30 seconds."); std::thread::sleep(Duration::from_secs(30)); } ``` -------------------------------- ### Watch Network Interface Changes Source: https://docs.rs/netwatcher Registers a callback to receive updates when network interfaces are added, removed, or modified. The returned handle must be kept in scope to continue receiving updates. ```rust let handle = netwatcher::watch_interfaces(|update| { // This callback will fire once immediately with the existing state // Update includes the latest snapshot of all interfaces println!("Current interface map: {:#?}", update.interfaces); // The `UpdateDiff` describes changes since previous callback // You can choose whether to use the snapshot, diff, or both println!("ifindexes added: {:?}", update.diff.added); println!("ifindexes removed: {:?}", update.diff.removed); for (ifindex, if_diff) in update.diff.modified { println!("Interface index {} has changed", ifindex); println!("Added IPs: {:?}", if_diff.addrs_added); println!("Removed IPs: {:?}", if_diff.addrs_removed); } }).unwrap(); // keep `handle` alive as long as you want callbacks // ... drop(handle); ``` -------------------------------- ### Implement From for T Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Provides a trivial conversion from a type T to itself. ```rust fn from(t: T) -> T ``` -------------------------------- ### watch_interfaces Source: https://docs.rs/netwatcher/0.4.1/netwatcher/fn.watch_interfaces.html Monitors network interface changes and triggers a callback with updates. ```APIDOC ## watch_interfaces ### Description Retrieve interface information and watch for changes, which will be delivered via callback. The callback fires immediately with an initial interface list. ### Parameters - **callback** (FnMut(Update) + Send + 'static) - Required - A closure that receives an Update object containing current interfaces and the diff. ### Response - **Result** - Returns a WatchHandle on success, which must be kept alive to continue receiving updates, or an Error if configuration fails. ``` -------------------------------- ### Blanket Implementations for WatchHandle Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.WatchHandle.html These are blanket implementations available for WatchHandle, leveraging generic trait implementations. ```APIDOC ## Blanket Implementations for WatchHandle ### impl Any for T #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. ### impl Borrow for T #### fn borrow(&self) -> &T Immutably borrows from an owned value. ### impl BorrowMut for T #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. ### impl From for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl Into for T #### fn into(self) -> U Calls `U::from(self)`. ### impl TryFrom for T #### type Error = Infallible #### fn try_from(value: U) -> Result>::Error> Performs the conversion. ### impl TryInto for T #### type Error = >::Error #### fn try_into(self) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Implement PartialEq for InterfaceDiff Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Enables equality comparison between InterfaceDiff instances. ```rust fn eq(&self, other: &InterfaceDiff) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### Implement TryInto for T Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Enables fallible conversion from type T to type U. ```rust type Error = >::Error ``` ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Define IpRecord struct Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.IpRecord.html The structure definition for IpRecord, containing an IP address and a prefix length. ```rust pub struct IpRecord { pub ip: IpAddr, pub prefix_len: u8, } ``` -------------------------------- ### Implement TryFrom for T Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Enables fallible conversion from type U to type T. ```rust type Error = Infallible ``` ```rust fn try_from(value: U) -> Result>::Error> ``` -------------------------------- ### Struct IpRecord Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.IpRecord.html Represents an IP address paired with its prefix length (network mask). ```APIDOC ## Struct IpRecord ### Description An IP address paired with its prefix length (network mask). ### Fields - `ip`: IpAddr - The IP address. - `prefix_len`: u8 - The prefix length (network mask). ### Trait Implementations - `Clone`: Allows creating copies of `IpRecord`. - `Debug`: Enables formatting `IpRecord` for debugging. - `Hash`: Allows hashing `IpRecord` instances. - `PartialEq`: Enables comparison of `IpRecord` instances for equality. - `Eq`: Indicates that `IpRecord` supports total equality. - `StructuralPartialEq`: For structural equality comparisons. ### Auto Trait Implementations - `Freeze`, `RefUnwindSafe`, `Send`, `Sync`, `Unpin`, `UnwindSafe` ``` -------------------------------- ### Implement Into for T Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Enables conversion from type T to type U if U implements From. ```rust fn into(self) -> U ``` -------------------------------- ### Implement Debug for InterfaceDiff Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Enables the InterfaceDiff struct to be formatted for debugging purposes. ```rust fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` -------------------------------- ### Implement Clone for InterfaceDiff Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Provides functionality to create a duplicate of an InterfaceDiff value. ```rust fn clone(&self) -> InterfaceDiff ``` ```rust fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### Auto Trait Implementations for WatchHandle Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.WatchHandle.html These are the auto-trait implementations provided for the WatchHandle struct. ```APIDOC ## Auto Trait Implementations for WatchHandle ### impl Freeze for WatchHandle ### impl RefUnwindSafe for WatchHandle ### impl Send for WatchHandle ### impl !Sync for WatchHandle ### impl Unpin for WatchHandle ### impl UnwindSafe for WatchHandle ``` -------------------------------- ### Implement Borrow for T Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Enables borrowing an immutable reference to T from T. ```rust fn borrow(&self) -> &T ``` -------------------------------- ### UpdateDiff Struct Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.UpdateDiff.html Represents the changes between two network updates. ```APIDOC ## Struct UpdateDiff ### Description What changed between one `Update` and the next. ### Fields - **added** (Vec) - A vector of interface IDs that were added. - **removed** (Vec) - A vector of interface IDs that were removed. - **modified** (HashMap) - A hash map where keys are interface IDs and values are `InterfaceDiff` structs detailing modifications. ### Example ```rust use std::collections::HashMap; // Assuming InterfaceDiff is defined elsewhere // struct InterfaceDiff { ... } let update_diff = UpdateDiff { added: vec![1, 2], removed: vec![3], modified: HashMap::from([(4, InterfaceDiff { ... })]), }; ``` ``` -------------------------------- ### Implement BorrowMut for T Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Enables borrowing a mutable reference to T from T. ```rust fn borrow_mut(&mut self) -> &mut T ``` -------------------------------- ### Struct InterfaceDiff Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Represents changes within a single network interface between updates. ```APIDOC ## Struct InterfaceDiff ### Description What changed within a single interface between updates, if it was present in both. ### Fields - **hw_addr_changed** (bool) - Indicates if the hardware address has changed. - **addrs_added** (Vec) - A list of IP records that were added. - **addrs_removed** (Vec) - A list of IP records that were removed. ### Trait Implementations #### impl Clone for InterfaceDiff - `fn clone(&self) -> InterfaceDiff`: Returns a duplicate of the value. - `fn clone_from(&mut self, source: &Self)`: Performs copy-assignment from `source`. #### impl Debug for InterfaceDiff - `fn fmt(&self, f: &mut Formatter<'_>) -> Result`: Formats the value using the given formatter. #### impl Default for InterfaceDiff - `fn default() -> InterfaceDiff`: Returns the default value for the type. #### impl PartialEq for InterfaceDiff - `fn eq(&self, other: &InterfaceDiff) -> bool`: Tests for equality between two `InterfaceDiff` instances. - `fn ne(&self, other: &Rhs) -> bool`: Tests for inequality. #### impl Eq for InterfaceDiff #### impl StructuralPartialEq for InterfaceDiff ### Auto Trait Implementations - Freeze - RefUnwindSafe - Send - Sync - Unpin - UnwindSafe ### Blanket Implementations - `impl Any for T` - `impl Borrow for T` - `impl BorrowMut for T` - `impl CloneToUninit for T` (Nightly-only experimental API) - `impl From for T` - `impl Into for T` - `impl ToOwned for T` - `impl TryFrom for T` - `impl TryInto for T` ``` -------------------------------- ### Update Struct Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.Update.html The Update struct contains information delivered via callback when a network interface change is detected. It includes up-to-date information about all interfaces and a diff detailing changes since the last callback. ```APIDOC ## Struct Update ### Description Information delivered via callback when a network interface change is detected. This contains up-to-date information about all interfaces, plus a diff which details which interfaces and IP addresses have changed since the last callback. ### Fields - **interfaces** (HashMap) - Contains up-to-date information about all network interfaces. - **diff** (UpdateDiff) - Details which interfaces and IP addresses have changed since the last callback. ### Trait Implementations - **Clone**: Allows creating a duplicate of the Update value. - **Debug**: Formats the value for debugging purposes. - **PartialEq**: Tests for equality between two Update values. - **Eq**: Indicates that equality is reflexive, symmetric, and transitive. - **StructuralPartialEq**: A marker trait for types that have structural equality. ### Auto Trait Implementations - **Freeze**, **RefUnwindSafe**, **Send**, **Sync**, **Unpin**, **UnwindSafe**: Standard Rust safety and concurrency traits. ``` -------------------------------- ### Define InterfaceDiff Struct Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Defines the structure for tracking changes in a network interface, including hardware address changes and added/removed IP addresses. ```rust pub struct InterfaceDiff { pub hw_addr_changed: bool, pub addrs_added: Vec, pub addrs_removed: Vec, } ``` -------------------------------- ### Implement Default for InterfaceDiff Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Provides a default value for the InterfaceDiff struct. ```rust fn default() -> InterfaceDiff ``` -------------------------------- ### Error Enum Variants Source: https://docs.rs/netwatcher/0.4.1/netwatcher/enum.Error.html A list of all variants available in the netwatcher::Error enum. ```APIDOC ## Error Enum Variants ### Description The `Error` enum captures various failure states during network monitoring tasks. It is marked as `#[non_exhaustive]`. ### Variants - **CreateSocket(String)** - Error creating a network socket. - **Bind(String)** - Error binding to a socket. - **CreatePipe(String)** - Error creating a pipe. - **Getifaddrs(String)** - Error retrieving interface addresses. - **GetInterfaceName(String)** - Error retrieving an interface name. - **FormatMacAddress** - Failed to format a MAC address. - **UnexpectedWindowsResult(u32)** - An unexpected result code from a Windows API call. - **AddressNotAssociated** - The address is not associated with an interface. - **InvalidParameter** - An invalid parameter was provided. - **NotEnoughMemory** - Insufficient memory available. - **InvalidHandle** - An invalid handle was encountered. - **NoAndroidContext** - No Android context available. - **Jni(String)** - A JNI-related error. - **Io(Error)** - An underlying I/O error. ``` -------------------------------- ### Trait Implementations for UpdateDiff Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.UpdateDiff.html Common trait implementations for the UpdateDiff struct. ```APIDOC ## Trait Implementations for UpdateDiff ### `impl Clone for UpdateDiff` Allows creating a copy of an `UpdateDiff` instance. #### Methods - `clone(&self) -> UpdateDiff`: Returns a duplicate of the value. - `clone_from(&mut self, source: &Self)`: Performs copy-assignment from `source`. ### `impl Debug for UpdateDiff` Enables formatting `UpdateDiff` instances for debugging. #### Methods - `fmt(&self, f: &mut Formatter<'_>) -> Result`: Formats the value using the given formatter. ### `impl Default for UpdateDiff` Provides a default value for `UpdateDiff`. #### Methods - `default() -> UpdateDiff`: Returns the default value for the type. ### `impl PartialEq for UpdateDiff` Allows comparison of two `UpdateDiff` instances for equality. #### Methods - `eq(&self, other: &UpdateDiff) -> bool`: Tests for equality. - `ne(&self, other: &Rhs) -> bool`: Tests for inequality. ### `impl Eq for UpdateDiff` Marks `UpdateDiff` as having a total equivalence relation. ``` -------------------------------- ### Implement Eq for InterfaceDiff Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Marks InterfaceDiff as having a total equivalence relation. -------------------------------- ### Implement ToOwned for T Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.InterfaceDiff.html Provides methods for creating owned data from borrowed data. ```rust type Owned = T ``` ```rust fn to_owned(&self) -> T ``` ```rust fn clone_into(&self, target: &mut T) ``` -------------------------------- ### WatchHandle Struct Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.WatchHandle.html The WatchHandle struct is a handle used to keep alive the mechanism for receiving callbacks. Dropping this handle will block until the current callback finishes and ensure no further callbacks are made. Care must be taken not to drop the handle from within a callback to avoid deadlocks. ```APIDOC ## Struct WatchHandle ### Description A handle to keep alive as long as you wish to receive callbacks. If the callback is executing at the time the handle is dropped, drop will block until the callback is finished and it’s guaranteed that it will not be called again. Do not drop the handle from within the callback itself. It will probably deadlock. ### Summary ```rust pub struct WatchHandle { /* private fields */ } ``` ``` -------------------------------- ### Interface Struct Definition Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.Interface.html The Interface struct represents a single network interface at a specific point in time. ```APIDOC ## Interface Struct ### Description Represents information about one network interface at a point in time. ### Fields - **index** (u32) - Internal index identifying this interface. - **name** (String) - Interface name. - **hw_addr** (String) - Hardware address. Android may have a placeholder due to privacy restrictions. - **ips** (Vec) - List of associated IPs and prefix length (netmask). ### Methods - **ipv4_ips()** -> impl Iterator: Helper to iterate over only the IPv4 addresses on this interface. - **ipv6_ips()** -> impl Iterator: Helper to iterate over only the IPv6 addresses on this interface. ``` -------------------------------- ### Define WatchHandle struct Source: https://docs.rs/netwatcher/0.4.1/netwatcher/struct.WatchHandle.html The definition of the WatchHandle struct with private fields. ```rust pub struct WatchHandle { /* private fields */ } ``` -------------------------------- ### Define Error Enum Source: https://docs.rs/netwatcher/0.4.1/netwatcher/enum.Error.html The Error enum captures errors from netwatcher or underlying platform integrations. It is marked as non-exhaustive, meaning new variants may be added in the future. ```rust #[non_exhaustive] pub enum Error { Show 14 variants CreateSocket(String), Bind(String), CreatePipe(String), Getifaddrs(String), GetInterfaceName(String), FormatMacAddress, UnexpectedWindowsResult(u32), AddressNotAssociated, InvalidParameter, NotEnoughMemory, InvalidHandle, NoAndroidContext, Jni(String), Io(Error), } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.