Created
April 25, 2024 18:17
-
-
Save vikpe/ec3f2f5de915c90005cf9c33ad6a0dd4 to your computer and use it in GitHub Desktop.
Convert host to IP address in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use anyhow::{anyhow as e, Result}; | |
pub async fn host_to_ip(host: &str) -> Result<String> { | |
match tokio::net::lookup_host(host).await { | |
Ok(mut ips) => { | |
if let Some(ip) = ips.next() { | |
Ok(ip.to_string()) | |
} else { | |
Err(e!("No IP address found for {}", host)) | |
} | |
} | |
Err(err) => Err(e!("Failed to lookup {}: {}", host, err)), | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use pretty_assertions::assert_eq; | |
use super::*; | |
#[tokio::test] | |
async fn test_host_to_ip() { | |
let ip = host_to_ip("quake.se:28000").await.ok(); | |
assert_eq!(ip, Some("46.227.68.148:28000".to_string())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment