1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use socket2::SockAddr;
use std::ffi::CStr;
use std::io;
use std::net::SocketAddr;
use std::str;
#[cfg(unix)]
use libc::{c_char, getnameinfo as c_getnameinfo};
#[cfg(windows)]
use winapi::ctypes::c_char;
#[cfg(windows)]
use winapi::um::ws2tcpip::getnameinfo as c_getnameinfo;
use err::LookupError;
pub fn getnameinfo(sock: &SocketAddr, flags: i32) -> Result<(String, String), LookupError> {
let sock: SockAddr = (*sock).into();
let c_sock = sock.as_ptr();
let c_sock_len = sock.len();
let mut c_host = [0 as c_char; 1024 as usize];
let mut c_service = [0 as c_char; 32 as usize];
#[cfg(windows)]
::win::init_winsock();
unsafe {
LookupError::match_gai_error(
c_getnameinfo(
c_sock, c_sock_len,
c_host.as_mut_ptr(),
c_host.len() as _,
c_service.as_mut_ptr(),
c_service.len() as _,
flags
)
)?;
}
let host = unsafe {
CStr::from_ptr(c_host.as_ptr())
};
let service = unsafe {
CStr::from_ptr(c_service.as_ptr())
};
let host = match str::from_utf8(host.to_bytes()) {
Ok(name) => Ok(name.to_owned()),
Err(_) => Err(io::Error::new(io::ErrorKind::Other,
"Host UTF8 parsing failed"))
}?;
let service = match str::from_utf8(service.to_bytes()) {
Ok(service) => Ok(service.to_owned()),
Err(_) => Err(io::Error::new(io::ErrorKind::Other,
"Service UTF8 parsing failed"))
}?;
Ok((host, service))
}
#[test]
fn test_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),
};
assert_eq!(service, "ssh");
#[cfg(unix)]
{
assert_eq!(name, "localhost");
}
#[cfg(windows)]
{
let hostname = ::hostname::get_hostname().unwrap();
assert_eq!(name, hostname);
}
}