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