| 1 |
use std::io; |
| 2 |
use std::net::IpAddr; |
| 3 |
use std::str; |
| 4 |
|
| 5 |
#[cfg(unix)] |
| 6 |
use libc::{NI_NUMERICSERV, SOCK_STREAM}; |
| 7 |
|
| 8 |
#[cfg(windows)] |
| 9 |
use winapi::shared::ws2def::{NI_NUMERICSERV, SOCK_STREAM}; |
| 10 |
|
| 11 |
use addrinfo::{getaddrinfo, AddrInfoHints}; |
| 12 |
use nameinfo::getnameinfo; |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
pub fn lookup_host(host: &str) -> io::Result<Vec<IpAddr>> { |
| 18 |
let hints = AddrInfoHints { |
| 19 |
socktype: SOCK_STREAM, |
| 20 |
..AddrInfoHints::default() |
| 21 |
}; |
| 22 |
|
| 23 |
match getaddrinfo(Some(host), None, Some(hints)) { |
| 24 |
Ok(addrs) => { |
| 25 |
let addrs: io::Result<Vec<_>> = addrs.map(|r| r.map(|a| a.sockaddr.ip())).collect(); |
| 26 |
addrs |
| 27 |
}, |
| 28 |
Err(e) => { |
| 29 |
reload_dns_nameserver(); |
| 30 |
Err(e)? |
| 31 |
}, |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
pub fn lookup_addr(addr: &IpAddr) -> io::Result<String> { |
| 39 |
let sock = (*addr, 0).into(); |
| 40 |
match getnameinfo(&sock, NI_NUMERICSERV) { |
| 41 |
Ok((name, _)) => Ok(name), |
| 42 |
Err(e) => { |
| 43 |
reload_dns_nameserver(); |
| 44 |
Err(e)? |
| 45 |
}, |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
fn reload_dns_nameserver() { |
| 54 |
cfg_if::cfg_if! { |
| 55 |
if #[cfg(target_os = "macos")] { |
| 56 |
} else if #[cfg(target_os = "ios")] { |
| 57 |
} else if #[cfg(unix)] { |
| 58 |
use libc; |
| 59 |
unsafe { |
| 60 |
libc::res_init(); |
| 61 |
} |
| 62 |
} |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
#[test] |
| 67 |
fn test_localhost() { |
| 68 |
let ips = lookup_host("localhost").unwrap(); |
| 69 |
assert!(ips.contains(&IpAddr::V4("127.0.0.1".parse().unwrap()))); |
| 70 |
assert!(!ips.contains(&IpAddr::V4("10.0.0.1".parse().unwrap()))); |
| 71 |
} |
| 72 |
|
| 73 |
#[cfg(unix)] |
| 74 |
#[test] |
| 75 |
fn test_rev_localhost() { |
| 76 |
let name = lookup_addr(&IpAddr::V4("127.0.0.1".parse().unwrap())); |
| 77 |
assert_eq!(name.unwrap(), "localhost"); |
| 78 |
} |
| 79 |
|
| 80 |
#[cfg(windows)] |
| 81 |
#[test] |
| 82 |
fn test_hostname() { |
| 83 |
|
| 84 |
let hostname = ::hostname::get_hostname().unwrap(); |
| 85 |
|
| 86 |
|
| 87 |
let rev_name = lookup_addr(&IpAddr::V4("127.0.0.1".parse().unwrap())); |
| 88 |
|
| 89 |
assert_eq!(rev_name.unwrap(), hostname); |
| 90 |
} |