hostname.c 1.8 KB

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