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
// Copyright (c) 2021 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
// Use of this source is governed by Apache-2.0 License that can be found
// in the LICENSE file.

//! Refers files in libc/misc/

use crate::core::str::cstr_to_str;
use crate::error::Error;

/// Get hostname.
pub fn gethostname() -> Result<String, Error> {
    let mut uts = nc::utsname_t::default();
    let _ = nc::uname(&mut uts)?;
    cstr_to_str(&uts.nodename).map(|s| s.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_gethostname() {
        let content = std::fs::read_to_string("/etc/hostname");
        assert!(content.is_ok());
        let content = content.unwrap();
        let content = content.trim();

        let h = gethostname();
        assert!(h.is_ok());
        let h = h.unwrap();
        assert_eq!(h, content);
    }
}