netwatcher/lib.rs
1//! # netwatcher
2//!
3//! `netwatcher` is a cross-platform library for enumerating network interfaces and their
4//! IP addresses, featuring the ability to watch for changes to those interfaces
5//! _efficiently_. It uses platform-specific methods to detect when interface changes
6//! have occurred instead of polling, which means that you find out about changes more
7//! quickly and there is no CPU or wakeup overhead when nothing is happening.
8//!
9//! ## List example
10//!
11//! ```
12//! /// Returns a HashMap from ifindex (a `u32`) to an `Interface` struct
13//! let interfaces = netwatcher::list_interfaces().unwrap();
14//! for i in interfaces.values() {
15//! println!("interface {}", i.name);
16//! for ip_record in &i.ips {
17//! println!("IP: {}/{}", ip_record.ip, ip_record.prefix_len);
18//! }
19//! }
20//! ```
21//!
22//! ## Watch example
23//!
24//! ```
25//! let handle = netwatcher::watch_interfaces(|update| {
26//! // This callback will fire once immediately with the existing state
27//!
28//! // Update includes the latest snapshot of all interfaces
29//! println!("Current interface map: {:#?}", update.interfaces);
30//!
31//! // The `UpdateDiff` describes changes since previous callback
32//! // You can choose whether to use the snapshot, diff, or both
33//! println!("ifindexes added: {:?}", update.diff.added);
34//! println!("ifindexes removed: {:?}", update.diff.removed);
35//! for (ifindex, if_diff) in update.diff.modified {
36//! println!("Interface index {} has changed", ifindex);
37//! println!("Added IPs: {:?}", if_diff.addrs_added);
38//! println!("Removed IPs: {:?}", if_diff.addrs_removed);
39//! }
40//! }).unwrap();
41//! // keep `handle` alive as long as you want callbacks
42//! // ...
43//! drop(handle);
44//! ```
45
46use std::{
47 collections::{HashMap, HashSet},
48 net::{IpAddr, Ipv4Addr, Ipv6Addr},
49 ops::Sub,
50};
51
52mod error;
53
54#[cfg_attr(windows, path = "list_win.rs")]
55#[cfg_attr(unix, path = "list_unix.rs")]
56mod list;
57
58#[cfg(target_os = "android")]
59mod android;
60
61#[cfg_attr(windows, path = "watch_win.rs")]
62#[cfg_attr(target_vendor = "apple", path = "watch_mac.rs")]
63#[cfg_attr(target_os = "linux", path = "watch_linux.rs")]
64#[cfg_attr(target_os = "android", path = "watch_android.rs")]
65mod watch;
66
67type IfIndex = u32;
68
69pub use error::Error;
70
71#[cfg(target_os = "android")]
72pub use android::set_android_context;
73
74/// An IP address paired with its prefix length (network mask).
75#[derive(Debug, Clone, PartialEq, Eq, Hash)]
76pub struct IpRecord {
77 pub ip: IpAddr,
78 pub prefix_len: u8,
79}
80
81/// Information about one network interface at a point in time.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct Interface {
84 /// Internal index identifying this interface.
85 pub index: u32,
86 /// Interface name.
87 pub name: String,
88 /// Hardware address. Android may have a placeholder due to privacy restrictions.
89 pub hw_addr: String,
90 /// List of associated IPs and prefix length (netmask).
91 pub ips: Vec<IpRecord>,
92}
93
94impl Interface {
95 /// Helper to iterate over only the IPv4 addresses on this interface.
96 pub fn ipv4_ips(&self) -> impl Iterator<Item = &Ipv4Addr> {
97 self.ips.iter().filter_map(|ip_record| match ip_record.ip {
98 IpAddr::V4(ref v4) => Some(v4),
99 IpAddr::V6(_) => None,
100 })
101 }
102
103 /// Helper to iterate over only the IPv6 addresses on this interface.
104 pub fn ipv6_ips(&self) -> impl Iterator<Item = &Ipv6Addr> {
105 self.ips.iter().filter_map(|ip_record| match ip_record.ip {
106 IpAddr::V4(_) => None,
107 IpAddr::V6(ref v6) => Some(v6),
108 })
109 }
110}
111
112/// Information delivered via callback when a network interface change is detected.
113///
114/// This contains up-to-date information about all interfaces, plus a diff which
115/// details which interfaces and IP addresses have changed since the last callback.
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub struct Update {
118 pub interfaces: HashMap<IfIndex, Interface>,
119 pub diff: UpdateDiff,
120}
121
122/// What changed between one `Update` and the next.
123#[derive(Debug, Clone, PartialEq, Eq, Default)]
124pub struct UpdateDiff {
125 pub added: Vec<IfIndex>,
126 pub removed: Vec<IfIndex>,
127 pub modified: HashMap<IfIndex, InterfaceDiff>,
128}
129
130/// What changed within a single interface between updates, if it was present in both.
131#[derive(Debug, Clone, PartialEq, Eq, Default)]
132pub struct InterfaceDiff {
133 pub hw_addr_changed: bool,
134 pub addrs_added: Vec<IpRecord>,
135 pub addrs_removed: Vec<IpRecord>,
136}
137
138#[derive(Default, PartialEq, Eq)]
139struct List(HashMap<IfIndex, Interface>);
140
141impl List {
142 fn diff_from(&self, prev: &List) -> UpdateDiff {
143 let prev_index_set: HashSet<IfIndex> = prev.0.keys().cloned().collect();
144 let curr_index_set: HashSet<IfIndex> = self.0.keys().cloned().collect();
145 let added = curr_index_set.sub(&prev_index_set).into_iter().collect();
146 let removed = prev_index_set.sub(&curr_index_set).into_iter().collect();
147 let mut modified = HashMap::new();
148 for index in curr_index_set.intersection(&prev_index_set) {
149 if prev.0[index] == self.0[index] {
150 continue;
151 }
152 let prev_addr_set: HashSet<&IpRecord> = prev.0[index].ips.iter().collect();
153 let curr_addr_set: HashSet<&IpRecord> = self.0[index].ips.iter().collect();
154 let addrs_added: Vec<IpRecord> = curr_addr_set
155 .sub(&prev_addr_set)
156 .iter()
157 .cloned()
158 .cloned()
159 .collect();
160 let addrs_removed: Vec<IpRecord> = prev_addr_set
161 .sub(&curr_addr_set)
162 .iter()
163 .cloned()
164 .cloned()
165 .collect();
166 let hw_addr_changed = prev.0[index].hw_addr != self.0[index].hw_addr;
167 modified.insert(
168 *index,
169 InterfaceDiff {
170 hw_addr_changed,
171 addrs_added,
172 addrs_removed,
173 },
174 );
175 }
176 UpdateDiff {
177 added,
178 removed,
179 modified,
180 }
181 }
182}
183
184/// A handle to keep alive as long as you wish to receive callbacks.
185///
186/// If the callback is executing at the time the handle is dropped, drop will block until
187/// the callback is finished and it's guaranteed that it will not be called again.
188///
189/// Do not drop the handle from within the callback itself. It will probably deadlock.
190pub struct WatchHandle {
191 _inner: watch::WatchHandle,
192}
193
194/// Retrieve information about all enabled network interfaces and their IP addresses.
195///
196/// This is a once-off operation. If you want to detect changes over time, see `watch_interfaces`.
197pub fn list_interfaces() -> Result<HashMap<IfIndex, Interface>, Error> {
198 list::list_interfaces().map(|list| list.0)
199}
200
201/// Retrieve interface information and watch for changes, which will be delivered via callback.
202///
203/// If setting up the watch is successful, this returns a `WatchHandle` which must be kept for
204/// as long as the provided callback should operate.
205///
206/// The callback will fire once immediately with an initial interface list, and a diff as if
207/// there were originally no interfaces present.
208///
209/// This function will return an error if there is a problem configuring the watcher, or if there
210/// is an error retrieving the initial interface list.
211///
212/// We assume that if listing the interfaces worked the first time, then it will continue to work
213/// for as long as the watcher is running. If listing interfaces begins to fail later, those
214/// failures will be swallowed and the callback will not be called for that change event.
215pub fn watch_interfaces<F: FnMut(Update) + Send + 'static>(
216 callback: F,
217) -> Result<WatchHandle, Error> {
218 watch::watch_interfaces(callback).map(|handle| WatchHandle { _inner: handle })
219}