### Testing Against the System Hostname Source: https://context7.com/swsnr/gethostname.rs/llms.txt Provides an example of how to test the `gethostname()` function against the operating system's reported hostname. This involves executing the system's `hostname` or `uname -n` command and comparing its output. ```APIDOC ## Testing Against the System Hostname ### Description The crate's own test suite demonstrates how to verify that the returned hostname matches the value reported by the operating system's `hostname` / `uname -n` command. ### Usage ```rust #[cfg(test)] mod tests { use gethostname::gethostname; use std::process::Command; #[test] fn verify_hostname_matches_os() { // Choose the appropriate OS command. let output = if cfg!(windows) { Command::new("hostname").output().unwrap() } else { Command::new("uname").arg("-n").output().unwrap() }; assert!(output.status.success(), "OS hostname command failed"); let os_hostname = String::from_utf8_lossy(&output.stdout); let os_hostname = os_hostname.trim_end(); // strip trailing newline let crate_hostname = gethostname().into_string().unwrap(); // Hostnames are case-insensitive. assert_eq!( crate_hostname.to_lowercase(), os_hostname.to_lowercase(), "gethostname() does not match OS hostname" ); } } ``` ``` -------------------------------- ### Using the Hostname in Structured Data Source: https://context7.com/swsnr/gethostname.rs/llms.txt Shows how to integrate the hostname retrieval into structured data formats, such as HashMaps, by converting the `OsString` to a `String` at application startup. This example includes handling potential non-UTF-8 hostnames. ```APIDOC ## Using Hostname in Structured Data ### Description `gethostname()` integrates naturally with serialization crates and structured logging by converting the `OsString` once at startup. ### Usage ```rust use gethostname::gethostname; use std::collections::HashMap; fn build_host_metadata() -> HashMap { let mut meta = HashMap::new(); let hostname = gethostname() .into_string() .unwrap_or_else(|_| String::from("")); meta.insert("hostname".to_string(), hostname); meta.insert("pid".to_string(), std::process::id().to_string()); meta } fn main() { let metadata = build_host_metadata(); for (key, value) in &metadata { println!("{}: {}", key, value); } } ``` ### Example Output ``` hostname: my-server pid: 12345 ``` ``` -------------------------------- ### Retrieve System Hostname as OsString Source: https://context7.com/swsnr/gethostname.rs/llms.txt Use the `gethostname()` function to get the hostname as an OsString. This preserves raw bytes and is safe for non-UTF-8 hostnames. It attempts a lossless conversion to a String. ```rust use gethostname::gethostname; use std::ffi::OsString; fn main() { // Retrieve the hostname as an OsString (platform-native string type). let hostname: OsString = gethostname(); // Display the raw debug form (works even for non-UTF-8 hostnames). println!("Hostname (raw): {:?}", hostname); // Attempt a lossless conversion to a Rust String. match hostname.into_string() { Ok(name) => println!("Hostname (UTF-8): {}", name), Err(os_str) => eprintln!("Hostname contains non-UTF-8 bytes: {:?}", os_str), } } ``` -------------------------------- ### Convert Hostname to String (Lossy) Source: https://context7.com/swsnr/gethostname.rs/llms.txt Use `to_string_lossy()` on the OsString hostname to get a String, replacing non-UTF-8 sequences with U+FFFD. This is useful for building identifiers or when a guaranteed String is needed. ```rust use gethostname::gethostname; fn main() { let hostname = gethostname(); // to_string_lossy() replaces any non-UTF-8 sequences with U+FFFD (). let hostname_str = hostname.to_string_lossy(); println!("Hostname: {}", hostname_str); // Common use: build a fully-qualified identifier. let service_id = format!("service-worker@{}", hostname_str); println!("Service ID: {}", service_id); // Service ID: service-worker@my-server } ``` -------------------------------- ### Get Hostname in Rust Source: https://github.com/swsnr/gethostname.rs/blob/main/README.md Use this snippet to retrieve the system's hostname. Ensure the `gethostname` crate is added as a dependency. ```rust use gethostname::gethostname; println!("Hostname: {:?}", gethostname()); ``` -------------------------------- ### Converting the Hostname to a String (Lossy) Source: https://context7.com/swsnr/gethostname.rs/llms.txt Demonstrates how to convert the `OsString` hostname to a `String` using `to_string_lossy()`. This method replaces any non-UTF-8 sequences with the Unicode replacement character (U+FFFD) and is useful when a guaranteed `String` is needed. ```APIDOC ## Converting Hostname to String (Lossy) ### Description When a guaranteed `String` is needed and non-UTF-8 hostnames can be handled by replacement, use the lossy conversion from `OsStr`. ### Usage ```rust use gethostname::gethostname; fn main() { let hostname = gethostname(); // to_string_lossy() replaces any non-UTF-8 sequences with U+FFFD (). let hostname_str = hostname.to_string_lossy(); println!("Hostname: {}", hostname_str); // Common use: build a fully-qualified identifier. let service_id = format!("service-worker@{}", hostname_str); println!("Service ID: {}", service_id); } ``` ### Example Output ``` Hostname: my-server Service ID: service-worker@my-server ``` ``` -------------------------------- ### Verify Hostname Matches OS Source: https://context7.com/swsnr/gethostname.rs/llms.txt This test verifies that the hostname returned by the crate matches the system's hostname obtained via OS commands (`hostname` or `uname -n`). It handles case-insensitivity. ```rust #[cfg(test)] mod tests { use gethostname::gethostname; use std::process::Command; #[test] fn verify_hostname_matches_os() { // Choose the appropriate OS command. let output = if cfg!(windows) { Command::new("hostname").output().unwrap() } else { Command::new("uname").arg("-n").output().unwrap() }; assert!(output.status.success(), "OS hostname command failed"); let os_hostname = String::from_utf8_lossy(&output.stdout); let os_hostname = os_hostname.trim_end(); // strip trailing newline let crate_hostname = gethostname().into_string().unwrap(); // Hostnames are case-insensitive. assert_eq!( crate_hostname.to_lowercase(), os_hostname.to_lowercase(), "gethostname() does not match OS hostname" ); } } ``` -------------------------------- ### Add gethostname Dependency to Cargo.toml Source: https://context7.com/swsnr/gethostname.rs/llms.txt Add this line to your Cargo.toml file to include the gethostname crate in your project. ```toml [dependencies] gethostname = "1.1.0" ``` -------------------------------- ### gethostname() — Retrieve the System Hostname Source: https://context7.com/swsnr/gethostname.rs/llms.txt This function returns the standard host name of the current machine as an OsString. It abstracts platform-specific calls to provide a unified interface. The returned value is the name configured on the host OS and does not guarantee DNS resolvability. ```APIDOC ## gethostname() ### Description Returns the standard host name of the current machine as an [`OsString`](https://doc.rust-lang.org/std/ffi/struct.OsString.html). On Unix, it calls `rustix::system::uname()` and extracts the node name. On Windows, it calls `GetComputerNameExW` with `ComputerNamePhysicalDnsHostname` to obtain the physical DNS hostname of the local computer. The returned value does not carry guarantees about DNS resolvability; it is simply the name configured on the host OS. ### Usage ```rust use gethostname::gethostname; use std::ffi::OsString; fn main() { // Retrieve the hostname as an OsString (platform-native string type). let hostname: OsString = gethostname(); // Display the raw debug form (works even for non-UTF-8 hostnames). println!("Hostname (raw): {:?}", hostname); // Attempt a lossless conversion to a Rust String. match hostname.into_string() { Ok(name) => println!("Hostname (UTF-8): {}", name), Err(os_str) => eprintln!("Hostname contains non-UTF-8 bytes: {:?}", os_str), } } ``` ### Example Output ``` Hostname (raw): "my-server" Hostname (UTF-8): my-server ``` ``` -------------------------------- ### Use Hostname in Structured Data Source: https://context7.com/swsnr/gethostname.rs/llms.txt Convert the OsString hostname to a String once at startup for use in structured data like HashMaps, suitable for serialization or logging. Handles potential non-UTF-8 hostnames gracefully. ```rust use gethostname::gethostname; use std::collections::HashMap; fn build_host_metadata() -> HashMap { let mut meta = HashMap::new(); let hostname = gethostname() .into_string() .unwrap_or_else(|_| String::from("")); meta.insert("hostname".to_string(), hostname); meta.insert("pid".to_string(), std::process::id().to_string()); meta } fn main() { let metadata = build_host_metadata(); for (key, value) in &metadata { println!("{}: {}", key, value); } // hostname: my-server // pid: 12345 } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.