]>
code.octet-stream.net Git - netwatcher/blob - src/lib.rs
2 collections
::{HashMap
, HashSet
},
3 net
::{IpAddr
, Ipv4Addr
, Ipv6Addr
},
7 #[cfg_attr(windows, path = "list_win.rs")]
8 #[cfg_attr(unix, path = "list_unix.rs")]
11 #[cfg_attr(windows, path = "watch_win.rs")]
12 #[cfg_attr(target_vendor = "apple", path = "watch_mac.rs")]
13 #[cfg_attr(target_os = "linux", path = "watch_linux.rs")]
18 #[derive(Debug, Clone, PartialEq, Eq)]
19 pub struct Interface
{
27 pub fn ipv4_ips(&self) -> impl Iterator
<Item
= &Ipv4Addr
> {
28 self.ips
.iter
().filter
_map
(|ip
| match ip
{
29 IpAddr
::V4(v4
) => Some(v4
),
30 IpAddr
::V6(_
) => None
,
34 pub fn ipv6_ips(&self) -> impl Iterator
<Item
= &Ipv6Addr
> {
35 self.ips
.iter
().filter
_map
(|ip
| match ip
{
36 IpAddr
::V4(_
) => None
,
37 IpAddr
::V6(v6
) => Some(v6
),
42 #[derive(Debug, Clone, PartialEq, Eq)]
44 pub interfaces
: HashMap
<IfIndex
, Interface
>,
48 #[derive(Debug, Clone, PartialEq, Eq, Default)]
49 pub struct UpdateDiff
{
50 pub added
: Vec
<IfIndex
>,
51 pub removed
: Vec
<IfIndex
>,
52 pub modified
: HashMap
<IfIndex
, InterfaceDiff
>,
55 #[derive(Debug, Clone, PartialEq, Eq, Default)]
56 pub struct InterfaceDiff
{
57 pub hw_addr_changed
: bool
,
58 pub addrs_added
: Vec
<IpAddr
>,
59 pub addrs_removed
: Vec
<IpAddr
>,
62 #[derive(Debug, Clone, PartialEq, Eq)]
64 // TODO: handle all cases with proper sources
68 #[derive(Default, PartialEq, Eq)]
69 struct List(HashMap
<IfIndex
, Interface
>);
72 fn diff_from(&self, prev
: &List
) -> UpdateDiff
{
73 let prev_index_set
: HashSet
<IfIndex
> = prev
.0.keys().cloned().collect();
74 let curr_index_set
: HashSet
<IfIndex
> = self.0.keys().cloned().collect();
75 let added
= curr_index_set
.sub(&prev_index_set
).into
_iter
().collect();
76 let removed
= prev_index_set
.sub(&curr_index_set
).into
_iter
().collect();
77 let mut modified
= HashMap
::new();
78 for index
in curr_index_set
.intersect
ion
(&prev_index_set
) {
79 if prev
.0[index
] == self.0[index
] {
82 let prev_addr_set
: HashSet
<&IpAddr
> = prev
.0[index
].ips
.iter
().collect();
83 let curr_addr_set
: HashSet
<&IpAddr
> = self.0[index
].ips
.iter
().collect();
84 let addrs_added
: Vec
<IpAddr
> = curr_addr_set
90 let addrs_removed
: Vec
<IpAddr
> = prev_addr_set
96 let hw_addr_changed
= prev
.0[index
].hw_addr
!= self.0[index
].hw_addr
;
114 pub struct WatchHandle
{
115 _inner
: watch
::WatchHandle
,
118 pub fn list_interfaces() -> Result
<HashMap
<IfIndex
, Interface
>, Error
> {
119 list
::list_interfaces().map(|list
| list
.0)
122 pub fn watch_interfaces
<F
: FnMut(Update
) + '
static>(callback
: F
) -> Result
<WatchHandle
, Error
> {
123 watch
::watch_interfaces(callback
).map(|handle
| WatchHandle
{ _inner
: handle
})