std/sys/net/hostname/
unix.rs

1use crate::ffi::OsString;
2use crate::io;
3use crate::os::unix::ffi::OsStringExt;
4use crate::sys::pal::os::errno;
5
6pub fn hostname() -> io::Result<OsString> {
7    // Query the system for the maximum host name length.
8    let host_name_max = match unsafe { libc::sysconf(libc::_SC_HOST_NAME_MAX) } {
9        // If this fails (possibly because there is no maximum length), then
10        // assume a maximum length of _POSIX_HOST_NAME_MAX (255).
11        -1 => 255,
12        max => max as usize,
13    };
14
15    // Reserve space for the nul terminator too.
16    let mut buf = Vec::<u8>::try_with_capacity(host_name_max + 1)?;
17    loop {
18        // SAFETY: `buf.capacity()` bytes of `buf` are writable.
19        let r = unsafe { libc::gethostname(buf.as_mut_ptr().cast(), buf.capacity()) };
20        match (r != 0).then(errno) {
21            None => {
22                // Unfortunately, the UNIX specification says that the name will
23                // be truncated if it does not fit in the buffer, without returning
24                // an error. As additionally, the truncated name may still be null-
25                // terminated, there is no reliable way to  detect truncation.
26                // Fortunately, most platforms ignore what the specification says
27                // and return an error (mostly ENAMETOOLONG). Should that not be
28                // the case, the following detects truncation if the null-terminator
29                // was omitted. Note that this check does not impact performance at
30                // all as we need to find the length of the string anyways.
31                //
32                // Use `strnlen` as it does not place an initialization requirement
33                // on the bytes after the nul terminator.
34                //
35                // SAFETY: `buf.capacity()` bytes of `buf` are accessible, and are
36                // initialized up to and including a possible nul terminator.
37                let len = unsafe { libc::strnlen(buf.as_ptr().cast(), buf.capacity()) };
38                if len < buf.capacity() {
39                    // If the string is nul-terminated, we assume that is has not
40                    // been truncated, as the capacity *should be* enough to hold
41                    // `HOST_NAME_MAX` bytes.
42                    // SAFETY: `len + 1` bytes have been initialized (we exclude
43                    // the nul terminator from the string).
44                    unsafe { buf.set_len(len) };
45                    return Ok(OsString::from_vec(buf));
46                }
47            }
48            // As `buf.capacity()` is always less than or equal to `isize::MAX`
49            // (Rust allocations cannot exceed that limit), the only way `EINVAL`
50            // can be returned is if the system uses `EINVAL` to report that the
51            // name does not fit in the provided buffer. In that case (or in the
52            // case of `ENAMETOOLONG`), resize the buffer and try again.
53            Some(libc::EINVAL | libc::ENAMETOOLONG) => {}
54            // Other error codes (e.g. EPERM) have nothing to do with the buffer
55            // size and should be returned to the user.
56            Some(err) => return Err(io::Error::from_raw_os_error(err)),
57        }
58
59        // Resize the buffer (according to `Vec`'s resizing rules) and try again.
60        buf.try_reserve(buf.capacity() + 1)?;
61    }
62}