hostname.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. char buf[256];
  20. if (!s)
  21. return;
  22. if (!isfile) {
  23. if (sethostname(s, strlen(s)) < 0) {
  24. if (errno == EPERM)
  25. bb_error_msg_and_die("you must be root to change the hostname");
  26. else
  27. bb_perror_msg_and_die("sethostname");
  28. }
  29. } else {
  30. f = xfopen(s, "r");
  31. while (fgets(buf, sizeof(buf), f) != NULL) {
  32. if (buf[0] =='#') {
  33. continue;
  34. }
  35. chomp(buf);
  36. do_sethostname(buf, 0);
  37. }
  38. #ifdef CONFIG_FEATURE_CLEAN_UP
  39. fclose(f);
  40. #endif
  41. }
  42. }
  43. int hostname_main(int argc, char **argv)
  44. {
  45. enum {
  46. OPT_d = 0x1,
  47. OPT_f = 0x2,
  48. OPT_i = 0x4,
  49. OPT_s = 0x8,
  50. OPT_dfis = 0xf,
  51. };
  52. char buf[256];
  53. unsigned opt;
  54. char *hostname_str = NULL;
  55. if (argc < 1)
  56. bb_show_usage();
  57. opt = getopt32(argc, argv, "dfisF:", &hostname_str);
  58. /* Output in desired format */
  59. if (opt & OPT_dfis) {
  60. struct hostent *hp;
  61. char *p;
  62. gethostname(buf, sizeof(buf));
  63. hp = xgethostbyname(buf);
  64. p = strchr(hp->h_name, '.');
  65. if (opt & OPT_f) {
  66. puts(hp->h_name);
  67. } else if (opt & OPT_s) {
  68. if (p != NULL) {
  69. *p = 0;
  70. }
  71. puts(hp->h_name);
  72. } else if (opt & OPT_d) {
  73. if (p) puts(p + 1);
  74. } else if (opt & OPT_i) {
  75. while (hp->h_addr_list[0]) {
  76. printf("%s ", inet_ntoa(*(struct in_addr *) (*hp->h_addr_list++)));
  77. }
  78. puts("");
  79. }
  80. }
  81. /* Set the hostname */
  82. else if (hostname_str != NULL) {
  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. }