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