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
#![deny(
missing_docs,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
variant_size_differences,
unused_features,
unused_results,
warnings
)]
use std::net::IpAddr;
use reqwest::Client;
use std::str::FromStr;
const IPV4_URL: &str = "https://api.ipify.org";
const IPV6_URL: &str = "https://api6.ipify.org";
pub async fn get_ip(prefer_ipv6: bool, client: Option<Client>) -> Result<IpAddr, IpRetrieveError> {
let client = client.unwrap_or_else(|| { Client::new() });
let url = if prefer_ipv6 {
IPV6_URL
} else {
IPV4_URL
};
let resp = client.get(url).send().await.map_err(|err| IpRetrieveError::Error(err.to_string()))?;
let text = resp.text().await.map_err(|err| IpRetrieveError::Error(err.to_string()))?;
IpAddr::from_str(text.as_str()).map_err(|err| IpRetrieveError::Error(err.to_string()))
}
#[derive(Debug)]
pub enum IpRetrieveError {
Error(String)
}