Skip to content

Instantly share code, notes, and snippets.

@vikpe
Created April 25, 2024 18:17
Show Gist options
  • Select an option

  • Save vikpe/ec3f2f5de915c90005cf9c33ad6a0dd4 to your computer and use it in GitHub Desktop.

Select an option

Save vikpe/ec3f2f5de915c90005cf9c33ad6a0dd4 to your computer and use it in GitHub Desktop.

Revisions

  1. vikpe created this gist Apr 25, 2024.
    27 changes: 27 additions & 0 deletions host_to_ip.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    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()));
    }
    }