3
0

hostname.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * $Id: hostname.c,v 1.36 2003/07/14 21:21:01 andersen Exp $
  4. * Mini hostname implementation for busybox
  5. *
  6. * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
  7. *
  8. * adjusted by Erik Andersen <andersen@codepoet.org> to remove
  9. * use of long options and GNU getopt. Improved the usage info.
  10. *
  11. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  12. *
  13. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  14. */
  15. #include "busybox.h"
  16. static void do_sethostname(char *s, int isfile)
  17. {
  18. FILE *f;
  19. if (!s)
  20. return;
  21. if (!isfile) {
  22. if (sethostname(s, strlen(s)) < 0) {
  23. if (errno == EPERM)
  24. bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
  25. else
  26. bb_perror_msg_and_die("sethostname");
  27. }
  28. } else {
  29. f = xfopen(s, "r");
  30. while (fgets(bb_common_bufsiz1, sizeof(bb_common_bufsiz1), f) != NULL) {
  31. if (bb_common_bufsiz1[0] == '#') {
  32. continue;
  33. }
  34. chomp(bb_common_bufsiz1);
  35. do_sethostname(bb_common_bufsiz1, 0);
  36. }
  37. if (ENABLE_FEATURE_CLEAN_UP)
  38. fclose(f);
  39. }
  40. }
  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_dfis = 0xf,
  49. };
  50. char buf[256];
  51. char *hostname_str = NULL;
  52. if (argc < 1)
  53. bb_show_usage();
  54. getopt32(argc, argv, "dfisF:", &hostname_str);
  55. /* Output in desired format */
  56. if (option_mask32 & OPT_dfis) {
  57. struct hostent *hp;
  58. char *p;
  59. gethostname(buf, sizeof(buf));
  60. hp = xgethostbyname(buf);
  61. p = strchr(hp->h_name, '.');
  62. if (option_mask32 & OPT_f) {
  63. puts(hp->h_name);
  64. } else if (option_mask32 & OPT_s) {
  65. if (p != NULL) {
  66. *p = 0;
  67. }
  68. puts(hp->h_name);
  69. } else if (option_mask32 & OPT_d) {
  70. if (p)
  71. puts(p + 1);
  72. } else if (option_mask32 & OPT_i) {
  73. while (hp->h_addr_list[0]) {
  74. printf("%s ", inet_ntoa(*(struct in_addr *) (*hp->h_addr_list++)));
  75. }
  76. puts("");
  77. }
  78. }
  79. /* Set the hostname */
  80. else if (hostname_str != NULL) {
  81. do_sethostname(hostname_str, 1);
  82. } else if (optind < argc) {
  83. do_sethostname(argv[optind], 0);
  84. }
  85. /* Or if all else fails,
  86. * just print the current hostname */
  87. else {
  88. gethostname(buf, sizeof(buf));
  89. puts(buf);
  90. }
  91. return 0;
  92. }