]>
code.octet-stream.net Git - netwatcher/blob - src/lib.rs
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.
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());
22 //! let handle = netwatcher::watch_interfaces(|update| {
23 //! // This callback will fire once immediately with the existing state
25 //! // Update includes the latest snapshot of all interfaces
26 //! println!("Current interface map: {:#?}", update.interfaces);
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);
38 //! // keep `handle` alive as long as you want callbacks
44 collections
::{HashMap
, HashSet
},
45 net
::{IpAddr
, Ipv4Addr
, Ipv6Addr
},
51 #[cfg_attr(windows, path = "list_win.rs")]
52 #[cfg_attr(unix, path = "list_unix.rs")]
55 #[cfg_attr(windows, path = "watch_win.rs")]
56 #[cfg_attr(target_vendor = "apple", path = "watch_mac.rs")]
58 any(target_os
= "linux", target_os
= "android"),
59 path
= "watch_linux.rs"
67 /// Information about one network interface at a point in time.
68 #[derive(Debug, Clone, PartialEq, Eq)]
69 pub struct 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
,
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
),
94 /// Information delivered via callback when a network interface change is detected.
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)]
100 pub interfaces
: HashMap
<IfIndex
, Interface
>,
101 pub diff
: UpdateDiff
,
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
>,
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
>,
120 #[derive(Default, PartialEq, Eq)]
121 struct List(HashMap
<IfIndex
, Interface
>);
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
.intersect
ion
(&prev_index_set
) {
131 if prev
.0[index
] == self.0[index
] {
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
142 let addrs_removed
: Vec
<IpAddr
> = prev_addr_set
148 let hw_addr_changed
= prev
.0[index
].hw_addr
!= self.0[index
].hw_addr
;
166 /// A handle to keep alive as long as you wish to receive callbacks.
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.
171 /// Do not drop the handle from within the callback itself. It will probably deadlock.
172 pub struct WatchHandle
{
173 _inner
: watch
::WatchHandle
,
176 /// Retrieve information about all enabled network interfaces and their IP addresses.
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)
183 /// Retrieve interface information and watch for changes, which will be delivered via callback.
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.
188 /// The callback will fire once immediately with an initial interface list, and a diff as if
189 /// there were originally no interfaces present.
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.
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>(
199 ) -> Result
<WatchHandle
, Error
> {
200 watch
::watch_interfaces(callback
).map(|handle
| WatchHandle
{ _inner
: handle
})