51 lines
1.3 KiB
Rust
51 lines
1.3 KiB
Rust
use anyhow::{anyhow, Context, Result};
|
|
use log::error;
|
|
use reqwest::Client;
|
|
use std::{collections::HashMap, net::Ipv4Addr};
|
|
|
|
async fn ipify_org(client: &Client) -> Result<Ipv4Addr> {
|
|
let response = client
|
|
.get("https://api.ipify.org?format=json")
|
|
.send()
|
|
.await?
|
|
.error_for_status()?
|
|
.json::<HashMap<String, String>>()
|
|
.await?;
|
|
|
|
Ok(response
|
|
.get("ip")
|
|
.context("Field 'ip' wasn't found")?
|
|
.parse()?)
|
|
}
|
|
|
|
async fn ifconfig_me(client: &Client) -> Result<Ipv4Addr> {
|
|
Ok(client
|
|
.get("https://ifconfig.me")
|
|
.header("user-agent", "curl/8.8.0")
|
|
.send()
|
|
.await?
|
|
.error_for_status()?
|
|
.text()
|
|
.await?
|
|
.parse()?)
|
|
}
|
|
|
|
pub async fn get_current_public_ipv4(client: &Client) -> Result<Ipv4Addr> {
|
|
let e_ipify = match ipify_org(client).await {
|
|
Ok(ipv4) => return Ok(ipv4),
|
|
Err(e) => {
|
|
error!("Failed to get ip from ipify.org: {:?}", &e);
|
|
e
|
|
}
|
|
};
|
|
|
|
ifconfig_me(client).await.map_err(|e_ifconfig| {
|
|
error!("Failed to get ip from ifconfig.me: {:?}", &e_ifconfig);
|
|
anyhow!(
|
|
"Failed to get ip from ipify.org with error '{:?}', and ifconfig.me with error {:?}",
|
|
&e_ipify,
|
|
&e_ifconfig
|
|
)
|
|
})
|
|
}
|