1#[cfg(target_os = "linux")]
2pub fn hostname() -> String {
3 use std::fs;
4
5 if let Ok(s) = fs::read_to_string("/etc/hostname") {
6 s.trim().to_owned()
7 } else {
8 "hostname".to_owned()
9 }
10}
11
12#[cfg(windows)]
13pub fn hostname() -> String {
14 use windows::{
15 core::PWSTR,
16 Win32::System::SystemInformation::{ComputerNamePhysicalDnsHostname, GetComputerNameExW},
17 };
18
19 let mut buffer_size: u32 = 0;
20 unsafe {
21 GetComputerNameExW(
22 ComputerNamePhysicalDnsHostname,
23 PWSTR::null(),
24 &mut buffer_size,
25 );
26 }
27
28 let mut buffer = vec![0_u16; buffer_size as usize];
29 unsafe {
30 GetComputerNameExW(
31 ComputerNamePhysicalDnsHostname,
32 PWSTR::from_raw(buffer.as_mut_ptr()),
33 &mut buffer_size,
34 );
35 }
36
37 String::from_utf16_lossy(&buffer)
38}
39
40#[cfg(not(any(target_os = "linux", windows)))]
41pub fn hostname() -> String {
42 use crate::get_output;
43
44 if let Ok(o) = get_output("hostname", &[]) {
45 o
46 } else {
47 "hostname".to_owned()
48 }
49}