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, ">1bdsfF:[!bdsf]", TOYFLAG_BIN))
8
9 config HOSTNAME
10 bool "hostname"
11 default y
12 help
13 usage: hostname [-bdsf] [-F FILENAME] [newname]
14
15 Get/set the current hostname.
16
17 -b Set hostname to 'localhost' if otherwise unset
18 -d Show DNS domain name (no host)
19 -f Show fully-qualified name (host+domain, FQDN)
20 -F Set hostname to contents of FILENAME
21 -s Show short host name (no domain)
22 */
23
24 #define FOR_hostname
25 #include "toys.h"
26
GLOBALS(char * F;)27 GLOBALS(
28 char *F;
29 )
30
31 void hostname_main(void)
32 {
33 char *hostname = *toys.optargs, *dot;
34 struct hostent *h;
35
36 if (TT.F && (hostname = xreadfile(TT.F, 0, 0))) {
37 if (!*chomp(hostname)) {
38 if (CFG_TOYBOX_FREE) free(hostname);
39 if (!FLAG(b)) error_exit("empty '%s'", TT.F);
40 hostname = 0;
41 }
42 }
43
44 // Implement -b.
45 if (!hostname && FLAG(b))
46 if (gethostname(toybuf, sizeof(toybuf)-1) || !*toybuf)
47 hostname = "localhost";
48
49 // Setting?
50 if (hostname) {
51 if (sethostname(hostname, strlen(hostname)))
52 perror_exit("set '%s'", hostname);
53 return;
54 }
55
56 // Get the hostname.
57 if (gethostname(toybuf, sizeof(toybuf)-1)) perror_exit("gethostname");
58 // We only do the DNS lookup for -d and -f.
59 if (FLAG(d) || FLAG(f)) {
60 if (!(h = gethostbyname(toybuf))) perror_exit("gethostbyname");
61 snprintf(toybuf, sizeof(toybuf), "%s", h->h_name);
62 }
63 dot = strchr(toybuf, '.');
64 if (FLAG(s) && dot) *dot = '\0';
65 xputs(FLAG(d) ? dot+1 : toybuf);
66 }
67