1
0
Fork 0
mirror of https://git.sr.ht/~spicywolf/k2spice synced 2025-01-18 09:49:38 +00:00

Add hostname

This commit is contained in:
Ezra Barrow 2023-11-14 02:35:05 -06:00
parent 56f461df4a
commit e160756d55
No known key found for this signature in database
GPG key ID: 5EF8BA3CE9180419
3 changed files with 90 additions and 0 deletions

View file

@ -8,4 +8,5 @@ members = [
"usr/src/mei/echo",
"usr/src/mei/printf",
"usr/src/mei/false",
"usr/src/mei/hostname",
]

View file

@ -0,0 +1,11 @@
[package]
name = "hostname"
version = "0.1.0"
edition = "2021"
[[bin]]
name = "hostname"
path = "src/hostname.rs"
[dependencies]
nix = { version = "0.27", features = ["hostname"] }

View file

@ -0,0 +1,78 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2023 Ezra Barrow All rights reserved.
* Use is subject to license terms.
*/
use nix::unistd::{gethostname, sethostname};
fn usage() {
println!("usage: hostname [-s] [system_name]");
}
//TODO: should probably involve a lot more osstrings as bytes rather than strings
fn main() -> Result<(), ()> {
let mut shortflag = false;
let mut newhostname = None;
for arg in std::env::args().skip(1) {
if arg == "-?" {
usage();
return Ok(());
} else if arg == "-s" {
shortflag = true;
} else if !arg.starts_with("-") {
if newhostname.replace(arg).is_some() {
usage();
return Ok(());
}
}
}
if let Some(hostname) = newhostname {
match sethostname(hostname) {
Ok(_) => Ok(()),
Err(e) => {
eprintln!("hostname: error in setting name: {}", e.desc());
Err(())
}
}
} else {
match gethostname() {
Ok(s) => {
if shortflag {
println!(
"{}",
s.to_string_lossy().split('.').nth(0).unwrap_or_default()
);
} else {
println!("{}", s.to_string_lossy());
};
Ok(())
}
Err(_) => {
eprintln!("hostname: unable to obtain hostname");
Err(())
}
}
}
}