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
//! Get hostname. Compatible with windows and linux.
//!
//! # Examples
//! ```
//! extern crate hostname;
//!
//! assert!(hostname::get_hostname().is_some());
//! ```
//!
#![cfg_attr(all(feature = "unstable", test), feature(test))]

#[cfg(windows)]
extern crate winutil;

#[cfg(unix)]
extern crate libc;


/// Get hostname.
#[cfg(windows)]
pub fn get_hostname() -> Option<String> {
    winutil::get_computer_name()
}


#[cfg(unix)]
extern "C" {
    fn gethostname(name: *mut libc::c_char, size: libc::size_t) -> libc::c_int;
}

#[cfg(unix)]
use std::ffi::CStr;

/// Get hostname.
#[cfg(unix)]
pub fn get_hostname() -> Option<String> {
    let len = 255;
    let mut buf = Vec::<u8>::with_capacity(len);
    let ptr = buf.as_mut_ptr() as *mut libc::c_char;

    unsafe {
        if gethostname(ptr, len as libc::size_t) != 0 {
            return None;
        }

        Some(CStr::from_ptr(ptr).to_string_lossy().into_owned())
    }
}

#[test]
fn test_get_hostname() {
    assert!(get_hostname().is_some());
    assert!(!get_hostname().unwrap().is_empty());
}

#[cfg(all(feature = "unstable", test))]
mod benches {
    extern crate test;
    use super::get_hostname;

    #[bench]
    fn bench_get_hostname(b: &mut test::Bencher) {
        b.iter(|| get_hostname().unwrap())
    }
}