hostname.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini hostname implementation for busybox
  4. *
  5. * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
  6. *
  7. * adjusted by Erik Andersen <andersen@codepoet.org> to remove
  8. * use of long options and GNU getopt. Improved the usage info.
  9. *
  10. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  11. *
  12. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  13. */
  14. #include "libbb.h"
  15. static void do_sethostname(char *s, int isfile)
  16. {
  17. if (!s)
  18. return;
  19. if (isfile) {
  20. parser_t *parser = config_open2(s, xfopen_for_read);
  21. while (config_read(parser, &s, 1, 1, "# \t", PARSE_NORMAL & ~PARSE_GREEDY)) {
  22. do_sethostname(s, 0);
  23. }
  24. if (ENABLE_FEATURE_CLEAN_UP)
  25. config_close(parser);
  26. } else if (sethostname(s, strlen(s)) < 0) {
  27. if (errno == EPERM)
  28. bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
  29. bb_perror_msg_and_die("sethostname");
  30. }
  31. }
  32. int hostname_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  33. int hostname_main(int argc, char **argv)
  34. {
  35. enum {
  36. OPT_d = 0x1,
  37. OPT_f = 0x2,
  38. OPT_i = 0x4,
  39. OPT_s = 0x8,
  40. OPT_F = 0x10,
  41. OPT_dfis = 0xf,
  42. };
  43. char *buf;
  44. char *hostname_str;
  45. if (argc < 1)
  46. bb_show_usage();
  47. getopt32(argv, "dfisF:", &hostname_str);
  48. argv += optind;
  49. buf = safe_gethostname();
  50. /* Output in desired format */
  51. if (option_mask32 & OPT_dfis) {
  52. struct hostent *hp;
  53. char *p;
  54. hp = xgethostbyname(buf);
  55. p = strchr(hp->h_name, '.');
  56. if (option_mask32 & OPT_f) {
  57. puts(hp->h_name);
  58. } else if (option_mask32 & OPT_s) {
  59. if (p)
  60. *p = '\0';
  61. puts(hp->h_name);
  62. } else if (option_mask32 & OPT_d) {
  63. if (p)
  64. puts(p + 1);
  65. } else if (option_mask32 & OPT_i) {
  66. while (hp->h_addr_list[0]) {
  67. printf("%s ", inet_ntoa(*(struct in_addr *) (*hp->h_addr_list++)));
  68. }
  69. bb_putchar('\n');
  70. }
  71. }
  72. /* Set the hostname */
  73. else if (option_mask32 & OPT_F) {
  74. do_sethostname(hostname_str, 1);
  75. } else if (argv[0]) {
  76. do_sethostname(argv[0], 0);
  77. }
  78. /* Or if all else fails,
  79. * just print the current hostname */
  80. else {
  81. puts(buf);
  82. }
  83. if (ENABLE_FEATURE_CLEAN_UP)
  84. free(buf);
  85. return EXIT_SUCCESS;
  86. }