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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#![warn(
clippy::pedantic,
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unsafe_op_in_unsafe_fn,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
variant_size_differences
)]
#![allow(
clippy::no_effect_underscore_binding
)]
pub mod gip;
pub mod hostip;
pub mod libc_getips;
use async_trait::async_trait;
use serde::Deserialize;
use std::net::IpAddr;
use thiserror::Error;
#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub enum IpScope {
Global,
Local,
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub enum IpType {
#[serde(rename = "IPv4")]
Ipv4,
#[serde(rename = "IPv6")]
Ipv6,
}
#[derive(Debug, Error)]
pub enum Error {
#[error(transparent)]
GlobalIpError(#[from] crate::gip::GlobalIpError),
#[error(transparent)]
AddrParseError(#[from] std::net::AddrParseError),
#[error(transparent)]
UnicodeParseError(#[from] std::string::FromUtf8Error),
#[error("Command exited with status {0}")]
NonZeroExit(std::process::ExitStatus),
#[error(transparent)]
IoError(#[from] std::io::Error),
#[error("no address returned")]
NoAddress,
}
pub type Result<R> = std::result::Result<R, Error>;
#[async_trait]
pub trait Provider: Sized {
async fn get_addr(&self) -> Result<IpAddr>;
fn get_type(&self) -> IpType;
}
pub async fn get_ip(ip_type: IpType, ip_scope: IpScope, nic: Option<&str>) -> Result<IpAddr> {
match (ip_type, ip_scope) {
(IpType::Ipv4, IpScope::Global) => {
let p = gip::ProviderMultiple::default();
p.get_addr().await
}
(IpType::Ipv6, IpScope::Global) => {
let p = gip::ProviderMultiple::default_v6();
p.get_addr().await
}
(IpType::Ipv4, IpScope::Local) => {
let p = hostip::LocalLibcProvider::new(nic, IpType::Ipv4);
p.get_addr().await
}
(IpType::Ipv6, IpScope::Local) => {
if let Some(nic) = nic {
let command_provider = hostip::LocalIpv6CommandProvider::new(nic, true);
let command_result = command_provider.get_addr().await;
if command_result.is_ok() || matches!(command_result, Err(Error::NoAddress)) {
return command_result;
}
};
let p = hostip::LocalLibcProvider::new(nic, IpType::Ipv6);
p.get_addr().await
}
}
}
#[cfg(test)]
mod test {
use crate::{get_ip, libc_getips, IpScope, IpType};
use std::net::IpAddr;
fn has_any_ipv6_address(iface_name: Option<&str>, global: bool) -> bool {
if let Ok(addresses) = libc_getips::get_iface_addrs(Some(IpType::Ipv6), iface_name) {
addresses
.iter()
.filter(|ip| {
!ip.is_loopback()
&& !ip.is_unspecified()
&& if global {
if let IpAddr::V6(dcasted) = ip {
(dcasted.segments()[0] & 0xffc0) != 0xfe80
&& (dcasted.segments()[0] & 0xfe00) != 0xfc00
} else {
unreachable!()
}
} else {
true
}
})
.next()
.is_some()
} else {
false
}
}
#[tokio::test]
async fn test_global_ipv4_is_any() {
let addr = get_ip(IpType::Ipv4, IpScope::Global, None).await;
assert!(addr.is_ok(), "The result of get_addr() should be Ok()");
if let IpAddr::V4(addr) = addr.unwrap() {
assert!(
!addr.is_private(),
"The result of get_addr() should not be private"
);
assert!(
!addr.is_loopback(),
"The result of get_addr() should not be loopback"
);
} else {
assert!(false, "The result of get_addr() should be an IPv4 address");
}
}
#[tokio::test]
async fn test_global_ipv6_is_any() {
if !has_any_ipv6_address(None, true) {
return;
}
let addr = get_ip(IpType::Ipv6, IpScope::Global, None).await;
assert!(addr.is_ok(), "The result of get_addr() should be Ok()");
if let IpAddr::V6(addr) = addr.unwrap() {
assert!(
!addr.is_loopback(),
"The result of get_addr() should not be loopback"
);
assert!(
!addr.is_unspecified(),
"The result of get_addr() should not be unspecified"
);
} else {
assert!(false, "The result of get_addr() should be an IPv6 address");
}
}
#[tokio::test]
async fn test_local_ipv4_is_any() {
let addr = get_ip(IpType::Ipv4, IpScope::Local, None).await;
assert!(addr.is_ok(), "The result of get_addr() should be Ok()");
if !addr.unwrap().is_ipv4() {
assert!(false, "The result of get_addr() should be an IPv4 address");
}
}
#[tokio::test]
async fn test_local_ipv6_is_any() {
if !has_any_ipv6_address(None, true) {
return;
}
let addr = get_ip(IpType::Ipv6, IpScope::Local, None).await;
assert!(addr.is_ok(), "The result of get_addr() should be Ok()");
if !addr.unwrap().is_ipv6() {
assert!(false, "The result of get_addr() should be an IPv6 address");
}
}
}