@@ -991,34 +991,34 @@ pub fn sethostname<S: AsRef<OsStr>>(name: S) -> Result<()> {
991
991
Errno :: result( res) . map( drop)
992
992
}
993
993
994
- /// Get the host name and store it in the provided buffer, returning a pointer
995
- /// the `CStr` in that buffer on success (see
994
+ /// Get the host name and store it in an internally allocated buffer, returning an
995
+ /// `OsString` on success (see
996
996
/// [gethostname(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/gethostname.html)).
997
997
///
998
998
/// This function call attempts to get the host name for the running system and
999
- /// store it in a provided buffer. The buffer will be populated with bytes up
1000
- /// to the length of the provided slice including a NUL terminating byte. If
1001
- /// the hostname is longer than the length provided, no error will be provided.
1002
- /// The posix specification does not specify whether implementations will
1003
- /// null-terminate in this case, but the nix implementation will ensure that the
1004
- /// buffer is null terminated in this case.
999
+ /// store it in an internal buffer, returning it as an `OsString` if successful.
1005
1000
///
1006
1001
/// ```no_run
1007
1002
/// use nix::unistd;
1008
1003
///
1009
- /// let mut buf = [0u8; 64];
1010
- /// let hostname_cstr = unistd::gethostname(&mut buf).expect("Failed getting hostname");
1011
- /// let hostname = hostname_cstr.to_str().expect("Hostname wasn't valid UTF-8");
1004
+ /// let hostname = unistd::gethostname().expect("Failed getting hostname");
1005
+ /// let hostname = hostname.into_string().expect("Hostname wasn't valid UTF-8");
1012
1006
/// println!("Hostname: {}", hostname);
1013
1007
/// ```
1014
- pub fn gethostname( buffer: & mut [ u8 ] ) -> Result <& CStr > {
1008
+ pub fn gethostname( ) -> Result <OsString > {
1009
+ // The capacity is the max length of a hostname plus the NUL terminator.
1010
+ let mut buffer: Vec <u8 > = Vec :: with_capacity( 256 ) ;
1015
1011
let ptr = buffer. as_mut_ptr( ) as * mut c_char;
1016
- let len = buffer. len ( ) as size_t;
1012
+ let len = buffer. capacity ( ) as size_t;
1017
1013
1018
1014
let res = unsafe { libc:: gethostname( ptr, len) } ;
1019
1015
Errno :: result( res) . map( |_| {
1020
- buffer[ len - 1 ] = 0 ; // ensure always null-terminated
1021
- unsafe { CStr :: from_ptr( buffer. as_ptr( ) as * const c_char) }
1016
+ unsafe {
1017
+ buffer. as_mut_ptr( ) . wrapping_add( len - 1 ) . write( 0 ) ; // ensure always null-terminated
1018
+ let len = CStr :: from_ptr( buffer. as_ptr( ) as * const c_char) . len( ) ;
1019
+ buffer. set_len( len) ;
1020
+ }
1021
+ OsString :: from_vec( buffer)
1022
1022
} )
1023
1023
}
1024
1024
}
0 commit comments