Added a method to store and get the previous IP.

This commit is contained in:
shad0wflame
2021-12-21 14:46:01 +01:00
parent 082daa4f90
commit 873e20195d
3 changed files with 57 additions and 6 deletions

View File

@@ -1,12 +1,35 @@
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use serde::{Serialize, Deserialize};
const FILE_NAME: &'static str = "ddns_ip";
#[derive(Deserialize)]
struct IP {
origin: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let ip = get_current_ip().await?;
let current_ip = get_current_ip().await?;
println!("{:#?}", ip);
let previous_ip = match check_previous_ip() {
Some(x) => x,
None => {
let mut file = File::create(FILE_NAME)?;
file.write_all(current_ip.as_ref())?;
String::new()
}
};
println!("Current IP: {}, Previous IP: {}", current_ip, previous_ip);
if current_ip.ne(&previous_ip) {
println!("Not equal!!!");
// TODO: GoDaddy connection.
}
Ok(())
}
@@ -14,8 +37,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
async fn get_current_ip() -> Result<String, Box<dyn std::error::Error>> {
let resp = reqwest::get("https://httpbin.org/ip")
.await?
.json::<HashMap<String, String>>()
.json::<IP>()
.await?;
Ok(resp.get("origin").unwrap().as_str().parse().unwrap())
Ok(resp.origin)
}
fn check_previous_ip() -> Option<String> {
if !Path::new(FILE_NAME).exists() {
return None;
}
let mut file = File::open(FILE_NAME).ok()?;
let mut contents = String::new();
file.read_to_string(&mut contents).expect("Error reading file");
return Some(contents);
}