Debian Codegraph @

src/hostname.rs

raw symbols SCIP
1 use std::ffi::CStr;
2 use std::io;
3 use std::str;
4
5 #[cfg(unix)]
6 use libc::{gethostname as c_gethostname, c_char};
7
8 #[cfg(windows)]
9 use winapi::ctypes::c_char;
10 #[cfg(windows)]
11 use winapi::um::winsock2::gethostname as c_gethostname;
12
13 /// Fetch the local hostname.
14 pub fn get_hostname() -> Result<String, io::Error> {
15 // Prime windows.
16 #[cfg(windows)]
17 ::win::init_winsock();
18
19 let mut c_name = [0 as c_char; 256 as usize];
20 let res = unsafe {
21 c_gethostname(c_name.as_mut_ptr(), c_name.len() as _)
22 };
23
24 // If an error occured, check errno for error message.
25 if res != 0 {
26 return Err(io::Error::last_os_error());
27 }
28
29 let hostname = unsafe {
30 CStr::from_ptr(c_name.as_ptr())
31 };
32
33 str::from_utf8(hostname.to_bytes())
34 .map(|h| h.to_owned())
35 .map_err(|_| io::Error::new(io::ErrorKind::Other, "Non-UTF8 hostname"))
36 }
37
38 #[test]
39 fn test_get_hostname() {
40 // We don't know the hostname of the local box, so just verify it doesn't return an error.
41 get_hostname().unwrap();
42 }