• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* hostname.c - Get/Set the hostname
2  *
3  * Copyright 2012 Andre Renaud <andre@bluewatersys.com>
4  *
5  * http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/hostname.html
6 
7 USE_HOSTNAME(NEWTOY(hostname, "bF:", TOYFLAG_BIN))
8 
9 config HOSTNAME
10   bool "hostname"
11   default y
12   help
13     usage: hostname [-b] [-F FILENAME] [newname]
14 
15     Get/Set the current hostname
16 
17     -b	Set hostname to 'localhost' if otherwise unset
18     -F	Set hostname to contents of FILENAME
19 */
20 
21 #define FOR_hostname
22 #include "toys.h"
23 
GLOBALS(char * fname;)24 GLOBALS(
25   char *fname;
26 )
27 
28 void hostname_main(void)
29 {
30   char *hostname = *toys.optargs;
31 
32   if (TT.fname && (hostname = xreadfile(TT.fname, 0, 0))) {
33     if (!*chomp(hostname)) {
34       if (CFG_TOYBOX_FREE) free(hostname);
35       if (!(toys.optflags&FLAG_b)) error_exit("empty '%s'", TT.fname);
36       hostname = 0;
37     }
38   }
39 
40   if (!hostname && (toys.optflags&FLAG_b))
41     if (gethostname(toybuf, sizeof(toybuf)-1) || !*toybuf)
42       hostname = "localhost";
43 
44   if (hostname) {
45     if (sethostname(hostname, strlen(hostname)))
46       perror_exit("set '%s'", hostname);
47   } else {
48     if (gethostname(toybuf, sizeof(toybuf)-1)) perror_exit("gethostname");
49     xputs(toybuf);
50   }
51 }
52