#ip-address #dns #lookup #resolve #getaddrinfo #getnameinfo

dns-lookup

A simple dns resolving api, much like rust's unstable api. Also includes getaddrinfo and getnameinfo wrappers for libc variants.

29 releases (14 stable)

2.0.4 Oct 15, 2023
2.0.2 May 13, 2023
1.0.8 Jul 17, 2021
1.0.6 Mar 24, 2021
0.2.0 Mar 26, 2016

#20 in Network programming

Download history 38988/week @ 2024-07-21 39224/week @ 2024-07-28 37198/week @ 2024-08-04 40111/week @ 2024-08-11 30689/week @ 2024-08-18 31621/week @ 2024-08-25 33562/week @ 2024-09-01 39094/week @ 2024-09-08 32825/week @ 2024-09-15 34061/week @ 2024-09-22 36568/week @ 2024-09-29 40101/week @ 2024-10-06 39529/week @ 2024-10-13 41533/week @ 2024-10-20 39224/week @ 2024-10-27 41492/week @ 2024-11-03

164,733 downloads per month
Used in 146 crates (81 directly)

MIT/Apache

34KB
627 lines

dns-lookup

Crates.io

A small wrapper for libc to perform simple DNS lookups.

You can use the lookup_host function to get a list of IP Addresses for a given hostname, and the lookup_name function to get the reverse dns entry for the given IP Address.

PS: If you only need a single result, consider ToSocketAddrs in libstd.

The library also includes a safe wrapper for getaddrinfo and getnameinfo.

Documentation

Usage

Simple API

use dns_lookup::{lookup_host, lookup_addr};

{
  let hostname = "localhost";
  let ips: Vec<std::net::IpAddr> = lookup_host(hostname).unwrap();
  assert!(ips.contains(&"127.0.0.1".parse().unwrap()));
}

{
  let ip: std::net::IpAddr = "127.0.0.1".parse().unwrap();
  let host = lookup_addr(&ip).unwrap();

  // The string "localhost" on unix, and the hostname on Windows.
}

libc API

{
  extern crate dns_lookup;

  use dns_lookup::{getaddrinfo, AddrInfoHints, SockType};

  fn main() {
    let hostname = "localhost";
    let service = "ssh";
    let hints = AddrInfoHints {
      socktype: SockType::Stream.into(),
      .. AddrInfoHints::default()
    };
    let sockets =
      getaddrinfo(Some(hostname), Some(service), Some(hints))
        .unwrap().collect::<std::io::Result<Vec<_>>>().unwrap();

    for socket in sockets {
      // Try connecting to socket
      println!("{:?}", socket);
    }
  }
}

{
  use dns_lookup::getnameinfo;
  use std::net::{IpAddr, SocketAddr};

  let ip: IpAddr = "127.0.0.1".parse().unwrap();
  let port = 22;
  let socket: SocketAddr = (ip, port).into();

  let (name, service) = match getnameinfo(&socket, 0) {
    Ok((n, s)) => (n, s),
    Err(e) => panic!("Failed to lookup socket {:?}", e),
  };

  println!("{:?} {:?}", name, service);
  let _ = (name, service);
}

{
  use dns_lookup::gethostname;

  let hostname = gethostname().unwrap();
}

Dependencies

~0.2–12MB
~75K SLoC