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