Skip to content

Instantly share code, notes, and snippets.

@vikpe
Created April 25, 2024 18:17
Show Gist options
  • Save vikpe/ec3f2f5de915c90005cf9c33ad6a0dd4 to your computer and use it in GitHub Desktop.
Save vikpe/ec3f2f5de915c90005cf9c33ad6a0dd4 to your computer and use it in GitHub Desktop.
Convert host to IP address in Rust
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