2 * $Id: hostname.c,v 1.1 1999/12/07 23:14:59 andersen Exp $
3 * Mini hostname implementation for busybox
5 * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include <arpa/inet.h>
30 static const char* hostname_usage = "hostname [OPTION] {hostname | -F file}\n\n"
32 "\t-s, --short\t\tshort\n"
33 "\t-i, --ip-address\t\taddresses for the hostname\n"
34 "\t-d, --domain\t\tDNS domain name\n"
35 "If a hostname is given, or a file is given with the -F parameter, the host\n"
38 static char short_opts[] = "sidF:";
39 static const struct option long_opts[] = {
40 { "short", no_argument, NULL, 's' },
41 { "ip-address", no_argument, NULL, 'i' },
42 { "domain", no_argument, NULL, 'd' },
46 void do_sethostname(char *s, int isfile)
53 if (sethostname(s, strlen(s)) < 0) {
55 fprintf(stderr, "hostname: you must be root to change the hostname\n");
57 perror("sethostname");
61 if ((f = fopen(s, "r")) == NULL) {
67 if (buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = 0;
68 if (sethostname(buf, strlen(buf)) < 0) {
69 perror("sethostname");
76 int hostname_main(int argc, char **argv)
84 char *filename = NULL;
88 if (argc < 1) usage(hostname_usage);
90 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
92 case 's': opt_short = 1; break;
93 case 'i': opt_ip = 1; break;
94 case 'd': opt_domain = 1; break;
95 case 'F': opt_file = 1; filename = optarg; break;
96 default: usage(hostname_usage);
101 do_sethostname(argv[optind], 0);
102 } else if (opt_file) {
103 do_sethostname(filename, 1);
105 gethostname(buf, 255);
107 s = strchr(buf, '.');
108 if (!s) s = buf; *s = 0;
110 } else if (opt_domain) {
111 s = strchr(buf, '.');
112 printf("%s\n", (s ? s+1 : ""));
114 h = gethostbyname(buf);
116 printf("Host not found\n");
119 printf("%s\n", inet_ntoa(*(struct in_addr *)(h->h_addr)));