| 1 | # dns-lookup |
| 2 | [](https://crates.io/crates/dns-lookup) |
| 3 | |
| 4 | A small wrapper for libc to perform simple DNS lookups. |
| 5 | |
| 6 | You can use the `lookup_host` function to get a list of IP Addresses for a |
| 7 | given hostname, and the `lookup_name` function to get the reverse dns entry for |
| 8 | the given IP Address. |
| 9 | |
| 10 | PS: If you only need a single result, consider |
| 11 | [ToSocketAddrs](https://doc.rust-lang.org/std/net/trait.ToSocketAddrs.html) in libstd. |
| 12 | |
| 13 | The library also includes a safe wrapper for `getaddrinfo` and `getnameinfo`. |
| 14 | |
| 15 | [Documentation](https://docs.rs/dns-lookup/) |
| 16 | |
| 17 | ## Usage |
| 18 | |
| 19 | ### Simple API |
| 20 | |
| 21 | ```rust |
| 22 | use dns_lookup::{lookup_host, lookup_addr}; |
| 23 | |
| 24 | { |
| 25 | let hostname = "localhost"; |
| 26 | let ips: Vec<std::net::IpAddr> = lookup_host(hostname).unwrap(); |
| 27 | assert!(ips.contains(&"127.0.0.1".parse().unwrap())); |
| 28 | } |
| 29 | |
| 30 | { |
| 31 | let ip: std::net::IpAddr = "127.0.0.1".parse().unwrap(); |
| 32 | let host = lookup_addr(&ip).unwrap(); |
| 33 | |
| 34 | // The string "localhost" on unix, and the hostname on Windows. |
| 35 | } |
| 36 | ``` |
| 37 | |
| 38 | ### libc API |
| 39 | ```rust |
| 40 | { |
| 41 | extern crate dns_lookup; |
| 42 | |
| 43 | use dns_lookup::{getaddrinfo, AddrInfoHints, SockType}; |
| 44 | |
| 45 | fn main() { |
| 46 | let hostname = "localhost"; |
| 47 | let service = "ssh"; |
| 48 | let hints = AddrInfoHints { |
| 49 | socktype: SockType::Stream.into(), |
| 50 | .. AddrInfoHints::default() |
| 51 | }; |
| 52 | let sockets = |
| 53 | getaddrinfo(Some(hostname), Some(service), Some(hints)) |
| 54 | .unwrap().collect::<std::io::Result<Vec<_>>>().unwrap(); |
| 55 | |
| 56 | for socket in sockets { |
| 57 | // Try connecting to socket |
| 58 | println!("{:?}", socket); |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | { |
| 64 | use dns_lookup::getnameinfo; |
| 65 | use std::net::{IpAddr, SocketAddr}; |
| 66 | |
| 67 | let ip: IpAddr = "127.0.0.1".parse().unwrap(); |
| 68 | let port = 22; |
| 69 | let socket: SocketAddr = (ip, port).into(); |
| 70 | |
| 71 | let (name, service) = match getnameinfo(&socket, 0) { |
| 72 | Ok((n, s)) => (n, s), |
| 73 | Err(e) => panic!("Failed to lookup socket {:?}", e), |
| 74 | }; |
| 75 | |
| 76 | println!("{:?} {:?}", name, service); |
| 77 | let _ = (name, service); |
| 78 | } |
| 79 | |
| 80 | { |
| 81 | use dns_lookup::gethostname; |
| 82 | |
| 83 | let hostname = gethostname().unwrap(); |
| 84 | } |
| 85 | ``` |