3
0

hostname.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. FILE *f;
  18. if (!s)
  19. return;
  20. if (!isfile) {
  21. if (sethostname(s, strlen(s)) < 0) {
  22. if (errno == EPERM)
  23. bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
  24. bb_perror_msg_and_die("sethostname");
  25. }
  26. } else {
  27. f = xfopen(s, "r");
  28. #define strbuf bb_common_bufsiz1
  29. while (fgets(strbuf, sizeof(strbuf), f) != NULL) {
  30. if (strbuf[0] == '#') {
  31. continue;
  32. }
  33. chomp(strbuf);
  34. do_sethostname(strbuf, 0);
  35. }
  36. if (ENABLE_FEATURE_CLEAN_UP)
  37. fclose(f);
  38. }
  39. }
  40. int hostname_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  41. int hostname_main(int argc, char **argv)
  42. {
  43. enum {
  44. OPT_d = 0x1,
  45. OPT_f = 0x2,
  46. OPT_i = 0x4,
  47. OPT_s = 0x8,
  48. OPT_F = 0x10,
  49. OPT_dfis = 0xf,
  50. };
  51. char *buf;
  52. char *hostname_str;
  53. if (argc < 1)
  54. bb_show_usage();
  55. getopt32(argv, "dfisF:", &hostname_str);
  56. argv += optind;
  57. buf = safe_gethostname();
  58. /* Output in desired format */
  59. if (option_mask32 & OPT_dfis) {
  60. struct hostent *hp;
  61. char *p;
  62. hp = xgethostbyname(buf);
  63. p = strchr(hp->h_name, '.');
  64. if (option_mask32 & OPT_f) {
  65. puts(hp->h_name);
  66. } else if (option_mask32 & OPT_s) {
  67. if (p)
  68. *p = '\0';
  69. puts(hp->h_name);
  70. } else if (option_mask32 & OPT_d) {
  71. if (p)
  72. puts(p + 1);
  73. } else if (option_mask32 & OPT_i) {
  74. while (hp->h_addr_list[0]) {
  75. printf("%s ", inet_ntoa(*(struct in_addr *) (*hp->h_addr_list++)));
  76. }
  77. bb_putchar('\n');
  78. }
  79. }
  80. /* Set the hostname */
  81. else if (option_mask32 & OPT_F) {
  82. do_sethostname(hostname_str, 1);
  83. } else if (argv[0]) {
  84. do_sethostname(argv[0], 0);
  85. }
  86. /* Or if all else fails,
  87. * just print the current hostname */
  88. else {
  89. puts(buf);
  90. }
  91. if (ENABLE_FEATURE_CLEAN_UP)
  92. free(buf);
  93. return 0;
  94. }