Returns the hostname of the current machine. Uses `libc::gethostname`. Returns `"unknown"` on any error (buffer too small, non-UTF-8, or syscall failure). Never panics.
()
| 39 | /// Uses `libc::gethostname`. Returns `"unknown"` on any error (buffer too small, |
| 40 | /// non-UTF-8, or syscall failure). Never panics. |
| 41 | pub fn hostname() -> String { |
| 42 | // POSIX guarantees HOST_NAME_MAX + 1 bytes is sufficient (typically 256). |
| 43 | // We use 256 to be safe across all platforms. |
| 44 | let mut buf = vec![0u8; 256]; |
| 45 | let result = unsafe { libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len()) }; |
| 46 | if result != 0 { |
| 47 | return "unknown".to_owned(); |
| 48 | } |
| 49 | // Find the null terminator. |
| 50 | let nul_pos = buf.iter().position(|&b| b == 0).unwrap_or(buf.len()); |
| 51 | String::from_utf8(buf[..nul_pos].to_vec()).unwrap_or_else(|_| "unknown".to_owned()) |
| 52 | } |
| 53 | |
| 54 | /// Returns the startup banner string. |
| 55 | /// |