#![deny(warnings, missing_docs, clippy::all, clippy::pedantic)]
#![cfg_attr(windows, allow(rustdoc::broken_intra_doc_links))]
use std::ffi::OsString;
#[must_use]
pub fn gethostname() -> OsString {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt;
OsString::from_vec(rustix::system::uname().nodename().to_bytes().to_vec())
}
#[cfg(windows)]
{
get_computer_physical_dns_hostname()
}
}
#[cfg(windows)]
fn get_computer_physical_dns_hostname() -> OsString {
use std::os::windows::ffi::OsStringExt;
pub const COMPUTER_NAME_PHYSICAL_DNS_HOSTNAME: i32 = 5;
::windows_link::link!("kernel32.dll" "system" fn GetComputerNameExW(nametype: i32, lpbuffer: *mut u16, nsize: *mut u32) -> i32);
let mut buffer_size: u32 = 0;
unsafe {
GetComputerNameExW(
COMPUTER_NAME_PHYSICAL_DNS_HOSTNAME,
std::ptr::null_mut(),
&mut buffer_size,
)
};
assert!(
0 < buffer_size,
"GetComputerNameExW did not provide buffer size"
);
let mut buffer = vec![0_u16; buffer_size as usize];
unsafe {
if GetComputerNameExW(
COMPUTER_NAME_PHYSICAL_DNS_HOSTNAME,
buffer.as_mut_ptr(),
&mut buffer_size,
) == 0
{
panic!(
"GetComputerNameExW failed to read hostname.
Please report this issue to <https://codeberg.org/swsnr/gethostname.rs/issues>!"
);
}
}
assert!(
buffer_size as usize == buffer.len() - 1,
"GetComputerNameExW changed the buffer size unexpectedly"
);
let end = buffer.iter().position(|&b| b == 0).unwrap_or(buffer.len());
OsString::from_wide(&buffer[0..end])
}
#[cfg(test)]
mod tests {
use std::process::Command;
#[test]
fn gethostname_matches_system_hostname() {
let mut command = if cfg!(windows) {
Command::new("hostname")
} else {
let mut uname = Command::new("uname");
uname.arg("-n");
uname
};
let output = command.output().expect("failed to get hostname");
if output.status.success() {
let hostname = String::from_utf8_lossy(&output.stdout);
assert!(
!hostname.is_empty(),
"Failed to get hostname: hostname empty?"
);
assert_eq!(
super::gethostname().into_string().unwrap().to_lowercase(),
hostname.trim_end().to_lowercase()
);
} else {
panic!(
"Failed to get hostname! {}",
String::from_utf8_lossy(&output.stderr)
);
}
}
}