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
use std::io;

use crate::scanner_rust::ScannerError;

/// Get the hostname using the `gethostname` function in libc.
///
/// ```rust
/// use mprober_lib::hostname;
///
/// let hostname = hostname::get_hostname().unwrap();
///
/// println!("{hostname}");
/// ```
#[inline]
pub fn get_hostname() -> Result<String, ScannerError> {
    let buffer_size = unsafe { libc::sysconf(libc::_SC_HOST_NAME_MAX) } as usize;

    let mut buffer: Vec<u8> = Vec::with_capacity(buffer_size);

    let c = unsafe { libc::gethostname(buffer.as_mut_ptr() as *mut libc::c_char, buffer_size) }
        as usize;

    if c != 0 {
        return Err(io::Error::last_os_error().into());
    }

    unsafe {
        buffer.set_len(buffer_size);
    }

    if let Some(end) = buffer.iter().copied().position(|e| e == b'\0') {
        unsafe {
            buffer.set_len(end);
        }
    }

    Ok(unsafe { String::from_utf8_unchecked(buffer) })
}