1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
|
use std::fmt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::ops::AddAssign;
use futures::future;
use futures::stream::{StreamExt, TryStreamExt};
use ipnet::{IpNet, Ipv4Net, Ipv6Net};
use netlink_packet_route::address::Nla::Address;
use netlink_packet_route::rtnl::constants::{AF_INET, AF_INET6};
use rtnetlink::new_connection;
use tokio::runtime::Runtime;
/// The errors that can occur when interacting with rtnetlink.
#[derive(Debug)]
pub enum Error {
RtNetlink(rtnetlink::Error),
IoError(std::io::Error),
LinkNotFound(Option<String>),
}
impl std::error::Error for Error {}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::RtNetlink(e) => write!(fmt, "rtnetlink error: {}", e),
Self::IoError(e) => write!(fmt, "rtnetlink connection failed: {}", e),
Self::LinkNotFound(filter) => match filter {
Some(link) => write!(fmt, "link not found: {}", link),
None => write!(fmt, "no links found"),
},
}
}
}
impl From<rtnetlink::Error> for Error {
fn from(e: rtnetlink::Error) -> Self {
Self::RtNetlink(e)
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Self::IoError(e)
}
}
/// An alias for `std::result::Result` that uses `Error`
/// as its error type.
pub type Result<T> = std::result::Result<T, Error>;
/// Get all IP addresses of an interface.
pub fn addresses(link: String) -> Result<Vec<IpNet>> {
let rt = Runtime::new()?;
rt.block_on(internal_addresses(Some(link)))
}
/// Get the IPv4 addresses of an interface.
pub fn ipv4_addresses(link: String) -> Result<Vec<Ipv4Net>> {
let addrs = addresses(link)?
.iter()
.filter_map(|addr| match addr {
IpNet::V4(addr) => Some(*addr),
IpNet::V6(_) => None,
})
.collect();
Ok(addrs)
}
/// Get the IPv6 addresses of an interface.
pub fn ipv6_addresses(link: String) -> Result<Vec<Ipv6Net>> {
let addrs = addresses(link)?
.iter()
.filter_map(|addr| match addr {
IpNet::V4(_) => None,
IpNet::V6(addr) => Some(*addr),
})
.collect();
Ok(addrs)
}
/// Get all IP addresses of this host.
pub fn all_addresses() -> Result<Vec<IpNet>> {
let rt = Runtime::new()?;
rt.block_on(internal_addresses(None))
}
/// Get the IPv4 addresses of this host.
pub fn all_ipv4_addresses() -> Result<Vec<Ipv4Net>> {
let addrs = all_addresses()?
.iter()
.filter_map(|addr| match addr {
IpNet::V4(addr) => Some(*addr),
IpNet::V6(_) => None,
})
.collect();
Ok(addrs)
}
/// Get the IPv6 addresses of this host.
pub fn all_ipv6_addresses() -> Result<Vec<Ipv6Net>> {
let addrs = all_addresses()?
.iter()
.filter_map(|addr| match addr {
IpNet::V4(_) => None,
IpNet::V6(addr) => Some(*addr),
})
.collect();
Ok(addrs)
}
/// Get the IP addresses. If filter is Some, limit the search
/// to that interface.
async fn internal_addresses(filter: Option<String>) -> Result<Vec<IpNet>> {
let (connection, handle, _) = new_connection()?;
tokio::spawn(connection);
let mut links = handle.link().get();
if let Some(link) = filter.clone() {
links = links.match_name(link);
}
let mut links = links.execute();
let mut num_links = 0_i32;
let mut link_addrs = Vec::new();
while let Some(link) = links.try_next().await? {
let addrs = handle
.address()
.get()
.set_link_index_filter(link.header.index)
.execute();
let addrs = addrs
.map_ok(|v| {
if let Some(Address(bytes)) = v.nlas.first() {
match v.header.family as u16 {
AF_INET => {
let octets: [u8; 4] = (*bytes).clone().try_into().unwrap();
let ip = IpAddr::from(Ipv4Addr::from(octets));
let net = IpNet::new(ip, v.header.prefix_len).unwrap();
Some(net)
}
AF_INET6 => {
let octets: [u8; 16] = (*bytes).clone().try_into().unwrap();
let ip = IpAddr::from(Ipv6Addr::from(octets));
let net = IpNet::new(ip, v.header.prefix_len).unwrap();
Some(net)
}
_ => None,
}
} else {
None
}
})
.try_filter(|v| future::ready(v.is_some()))
.filter_map(|v| future::ready(v.unwrap()));
link_addrs.append(&mut addrs.collect::<Vec<IpNet>>().await);
num_links.add_assign(1);
}
if num_links > 0 {
Ok(link_addrs)
} else {
Err(Error::LinkNotFound(filter))
}
}
|