std\sys\net\hostname/
windows.rs

1use crate::ffi::OsString;
2use crate::io::Result;
3use crate::mem::MaybeUninit;
4use crate::os::windows::ffi::OsStringExt;
5use crate::sys::pal::c;
6use crate::sys::pal::winsock::{self, cvt};
7
8pub fn hostname() -> Result<OsString> {
9    winsock::startup();
10
11    // The documentation of GetHostNameW says that a buffer size of 256 is
12    // always enough.
13    let mut buffer = [const { MaybeUninit::<u16>::uninit() }; 256];
14    // SAFETY: these parameters specify a valid, writable region of memory.
15    cvt(unsafe { c::GetHostNameW(buffer.as_mut_ptr().cast(), buffer.len() as i32) })?;
16    // Use `lstrlenW` here as it does not require the bytes after the nul
17    // terminator to be initialized.
18    // SAFETY: if `GetHostNameW` returns successfully, the name is nul-terminated.
19    let len = unsafe { c::lstrlenW(buffer.as_ptr().cast()) };
20    // SAFETY: the length of the name is `len`, hence `len` bytes have been
21    //         initialized by `GetHostNameW`.
22    let name = unsafe { buffer[..len as usize].assume_init_ref() };
23    Ok(OsString::from_wide(name))
24}