2022-08-23 00:17:17 -05:00
|
|
|
use async_trait::async_trait;
|
|
|
|
|
2023-02-10 21:08:54 -06:00
|
|
|
use crate::ClientError;
|
|
|
|
|
2022-08-23 00:17:17 -05:00
|
|
|
use super::ip_source::IPSource;
|
|
|
|
|
2023-01-31 23:21:02 -06:00
|
|
|
pub(crate) struct IPSourceIcanhazip;
|
2022-08-23 00:17:17 -05:00
|
|
|
|
2023-02-10 21:08:54 -06:00
|
|
|
async fn get_ip(api_url: &str) -> Result<String, ClientError> {
|
2022-08-23 00:17:17 -05:00
|
|
|
let response = reqwest::get(api_url).await?;
|
|
|
|
let text = response.text().await?;
|
|
|
|
Ok(text)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[async_trait]
|
|
|
|
impl IPSource for IPSourceIcanhazip {
|
2023-02-10 21:08:54 -06:00
|
|
|
async fn get_ipv4(&self) -> Result<String, ClientError> {
|
2022-08-23 00:17:17 -05:00
|
|
|
Ok(get_ip("https://ipv4.icanhazip.com")
|
|
|
|
.await?
|
|
|
|
// icanazip puts a newline at the end
|
|
|
|
.trim()
|
|
|
|
.to_string())
|
|
|
|
}
|
2023-02-10 21:08:54 -06:00
|
|
|
async fn get_ipv6(&self) -> Result<String, ClientError> {
|
2022-08-23 00:17:17 -05:00
|
|
|
Ok(get_ip("https://ipv6.icanhazip.com")
|
|
|
|
.await?
|
|
|
|
// icanazip puts a newline at the end
|
|
|
|
.trim()
|
|
|
|
.to_string())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use regex::Regex;
|
|
|
|
|
2023-01-31 23:21:02 -06:00
|
|
|
use crate::ip_source::ip_source::IPSource;
|
|
|
|
|
2022-08-23 00:17:17 -05:00
|
|
|
use super::IPSourceIcanhazip;
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
#[ignore]
|
|
|
|
async fn ipv4_test() {
|
2023-01-31 23:21:02 -06:00
|
|
|
let ipv4 = IPSourceIcanhazip
|
|
|
|
.get_ipv4()
|
2022-08-23 00:17:17 -05:00
|
|
|
.await
|
|
|
|
.expect("Failed to get the IP address");
|
|
|
|
assert!(Regex::new(r"^\d+[.]\d+[.]\d+[.]\d+$")
|
|
|
|
.unwrap()
|
|
|
|
.is_match(ipv4.as_str()))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
#[ignore]
|
|
|
|
async fn ipv6_test() {
|
2023-01-31 23:21:02 -06:00
|
|
|
let ipv6 = IPSourceIcanhazip
|
|
|
|
.get_ipv6()
|
2022-08-23 00:17:17 -05:00
|
|
|
.await
|
|
|
|
.expect("Failed to get the IP address");
|
|
|
|
assert!(Regex::new(r"^([0-9a-fA-F]*:){7}[0-9a-fA-F]*$")
|
|
|
|
.unwrap()
|
|
|
|
.is_match(ipv6.as_str()))
|
|
|
|
}
|
|
|
|
}
|