dns_lookup/
hostname.rs

1use std::ffi::CStr;
2use std::io;
3use std::os::raw::c_char;
4use std::str;
5
6#[cfg(unix)]
7use libc::{c_char as libc_c_char, gethostname as c_gethostname};
8
9#[cfg(windows)]
10#[allow(non_camel_case_types)]
11type libc_c_char = u8;
12#[cfg(windows)]
13use windows_sys::Win32::Networking::WinSock::gethostname as c_gethostname;
14
15/// Fetch the local hostname.
16pub fn get_hostname() -> Result<String, io::Error> {
17    // Prime windows.
18    #[cfg(windows)]
19    crate::win::init_winsock();
20
21    let mut c_name = [0 as c_char; 256_usize];
22
23    let res = unsafe { c_gethostname(c_name.as_mut_ptr() as *mut libc_c_char, c_name.len() as _) };
24
25    // If an error occured, check errno for error message.
26    if res != 0 {
27        return Err(io::Error::last_os_error());
28    }
29
30    let hostname = unsafe { CStr::from_ptr(c_name.as_ptr() as *const c_char) };
31
32    str::from_utf8(hostname.to_bytes())
33        .map(|h| h.to_owned())
34        .map_err(|_| io::Error::new(io::ErrorKind::Other, "Non-UTF8 hostname"))
35}
36
37#[test]
38fn test_get_hostname() {
39    // We don't know the hostname of the local box, so just verify it doesn't return an error.
40    get_hostname().unwrap();
41}