From 0973bca227404d1d66a7aef9130cadeb67e3d2f6 Mon Sep 17 00:00:00 2001 From: Love Billenius Date: Sun, 14 Jul 2024 12:50:06 +0200 Subject: [PATCH] public ip --- src/cloudflare.rs | 19 +++---------------- src/lib.rs | 5 +++-- src/public_ip.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 18 deletions(-) create mode 100644 src/public_ip.rs diff --git a/src/cloudflare.rs b/src/cloudflare.rs index 837e550..41796df 100644 --- a/src/cloudflare.rs +++ b/src/cloudflare.rs @@ -8,6 +8,8 @@ use std::{ sync::Arc, }; +use crate::get_current_public_ipv4; + pub struct CloudflareClient { client: Client, domains: Vec>, @@ -15,21 +17,6 @@ pub struct CloudflareClient { api_key: Box, zone_id: Box, } -// Some external site to check this -async fn get_current_public_ipv4(client: &Client) -> Result { - let response = client - .get("https://api.ipify.org?format=json") - .send() - .await? - .error_for_status()? - .json::>() - .await?; - - Ok(response - .get("ip") - .context("Field 'ip' wasn't found")? - .parse()?) -} #[derive(Serialize, Deserialize, Clone, Debug)] struct DnsRecord { @@ -45,7 +32,7 @@ struct DnsRecord { zone_name: Box, modified_on: Box, created_on: Box, - meta: HashMap, + meta: HashMap, serde_json::Value>, } impl CloudflareClient { diff --git a/src/lib.rs b/src/lib.rs index 9c3782b..e335333 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ mod cloudflare; mod config; -pub use config::{Config, get_config_path, read_config}; - +mod public_ip; +pub use config::{get_config_path, read_config, Config}; +pub use public_ip::get_current_public_ipv4; pub const PROGRAM_NAME: &'static str = "dynip-cloudflare"; diff --git a/src/public_ip.rs b/src/public_ip.rs new file mode 100644 index 0000000..b3329fe --- /dev/null +++ b/src/public_ip.rs @@ -0,0 +1,44 @@ + use anyhow::{anyhow, Context, Result}; + use log::error; + use reqwest::Client; + use std::{collections::HashMap, net::Ipv4Addr}; + + async fn ipify_org(client: &Client) -> Result { + let response = client + .get("https://api.ipify.org?format=json") + .send() + .await? + .error_for_status()? + .json::>() + .await?; + + Ok(response + .get("ip") + .context("Field 'ip' wasn't found")? + .parse()?) + } + async fn ifconfig_me(client: &Client) -> Result { + 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 { + 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) + }) + } \ No newline at end of file