Mercurial > lbo > hg > syslog
view src/util.rs @ 28:07f67992c899 draft default tip
Implement gethostname/getfullhostname utility functions
author | Lewin Bormann <lbo@spheniscida.de> |
---|---|
date | Sun, 04 Dec 2016 17:48:14 +0100 |
parents | |
children |
line wrap: on
line source
use libc; pub fn getfullhostname() -> Option<String> { const MAX_HOSTNAME_LENGTH: usize = 255; // Max possible size as specified by POSIX let mut dest = [0 as i8; MAX_HOSTNAME_LENGTH]; unsafe { let err = libc::gethostname(&mut dest[0] as *mut libc::c_char, MAX_HOSTNAME_LENGTH as libc::size_t); if err == 0 { match String::from_utf8(dest.into_iter() .filter(|c| **c > 0) .map(|c| *c as u8) .collect()) { Ok(s) => Some(s), Err(_) => None, } } else { None } } } pub fn gethostname() -> Option<String> { getfullhostname().and_then(|s| s.split('.').next().map(|s| s.to_string())) } #[cfg(test)] mod tests { #[test] fn test_util_gethostname() { println!("{:?}", super::gethostname()); println!("{:?}", super::getfullhostname()); } }