|
1 | 1 | #[cfg(test)] |
2 | 2 | mod tests; |
3 | 3 |
|
4 | | -use crate::ffi::{c_int, c_void}; |
| 4 | +use crate::ffi::{CStr, OsString, c_char, c_int, c_void}; |
5 | 5 | use crate::io::{self, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut}; |
6 | 6 | use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; |
7 | 7 | use crate::sys::common::small_c_string::run_with_cstr; |
@@ -215,6 +215,31 @@ impl<'a> TryFrom<(&'a str, u16)> for LookupHost { |
215 | 215 | } |
216 | 216 | } |
217 | 217 |
|
| 218 | +//////////////////////////////////////////////////////////////////////////////// |
| 219 | +// gethostname |
| 220 | +//////////////////////////////////////////////////////////////////////////////// |
| 221 | + |
| 222 | +pub fn gethostname() -> crate::io::Result<OsString> { |
| 223 | + init(); |
| 224 | + // 255 bytes is the maximum allowable length for a hostname (as per the DNS spec), |
| 225 | + // so we shouldn't ever have problems with this. I (@orowith2os) considered using a constant |
| 226 | + // and letting the platform set the length, but it was determined after some discussion that |
| 227 | + // this could break things if the platform changes their length. Possible alternative is to |
| 228 | + // read the sysconf setting for the max hostname length, but that might be a bit too much work. |
| 229 | + // The 256 byte length is to allow for the NUL terminator. |
| 230 | + let mut temp_buffer: [c_char; 256] = [0; 256]; |
| 231 | + |
| 232 | + // SAFETY: should never be unsafe, as we're passing in a valid (0-initialized) buffer, and the |
| 233 | + // length of said buffer. |
| 234 | + unsafe { |
| 235 | + cvt(c::gethostname(temp_buffer.as_mut_ptr() as _, temp_buffer.len() as _))?; |
| 236 | + } |
| 237 | + |
| 238 | + // SAFETY: we already know the pointer here is valid, we made it from safe Rust earlier. |
| 239 | + let cstring = unsafe { CStr::from_ptr(temp_buffer.as_mut_ptr()) }; |
| 240 | + Ok(OsString::from(cstring.to_string_lossy().as_ref())) |
| 241 | +} |
| 242 | + |
218 | 243 | //////////////////////////////////////////////////////////////////////////////// |
219 | 244 | // TCP streams |
220 | 245 | //////////////////////////////////////////////////////////////////////////////// |
|
0 commit comments