1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24#define FOR_hostname
25#include "toys.h"
26
27GLOBALS(
28 char *F;
29)
30
31void 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
45 if (!hostname && FLAG(b))
46 if (gethostname(toybuf, sizeof(toybuf)-1) || !*toybuf)
47 hostname = "localhost";
48
49
50 if (hostname) {
51 if (sethostname(hostname, strlen(hostname)))
52 perror_exit("set '%s'", hostname);
53 return;
54 }
55
56
57 if (gethostname(toybuf, sizeof(toybuf)-1)) perror_exit("gethostname");
58
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