1 /* hostname - set or print the name of current host system
2 Copyright (C) 1994-1997, 1999-2005, 2007-2008 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Jim Meyering. */
22 #include <sys/types.h>
25 #include "long-options.h"
28 #include "xgethostname.h"
30 /* The official name of this program (e.g., no `g' prefix). */
31 #define PROGRAM_NAME "hostname"
33 #define AUTHORS proper_name ("Jim Meyering")
35 #if HAVE_SETHOSTNAME && !defined sethostname
39 #if !defined HAVE_SETHOSTNAME && defined HAVE_SYSINFO && \
40 defined HAVE_SYS_SYSTEMINFO_H
41 # include <sys/systeminfo.h>
44 sethostname (char *name, size_t namelen)
46 /* Using sysinfo() is the SVR4 mechanism to set a hostname. */
47 return (sysinfo (SI_SET_HOSTNAME, name, namelen) < 0 ? -1 : 0);
50 # define HAVE_SETHOSTNAME 1 /* Now we have it... */
56 if (status != EXIT_SUCCESS)
57 fprintf (stderr, _("Try `%s --help' for more information.\n"),
64 Print or set the hostname of the current system.\n\
67 program_name, program_name);
68 fputs (HELP_OPTION_DESCRIPTION, stdout);
69 fputs (VERSION_OPTION_DESCRIPTION, stdout);
70 emit_bug_reporting_address ();
76 main (int argc, char **argv)
80 initialize_main (&argc, &argv);
81 set_program_name (argv[0]);
82 setlocale (LC_ALL, "");
83 bindtextdomain (PACKAGE, LOCALEDIR);
86 atexit (close_stdout);
88 parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, VERSION,
89 usage, AUTHORS, (char const *) NULL);
90 if (getopt_long (argc, argv, "", NULL, NULL) != -1)
93 if (argc == optind + 1)
95 #ifdef HAVE_SETHOSTNAME
96 /* Set hostname to operand. */
97 char const *name = argv[optind];
98 if (sethostname (name, strlen (name)) != 0)
99 error (EXIT_FAILURE, errno, _("cannot set name to %s"), quote (name));
101 error (EXIT_FAILURE, 0,
102 _("cannot set hostname; this system lacks the functionality"));
108 hostname = xgethostname ();
109 if (hostname == NULL)
110 error (EXIT_FAILURE, errno, _("cannot determine hostname"));
111 printf ("%s\n", hostname);
114 if (optind + 1 < argc)
116 error (0, 0, _("extra operand %s"), quote (argv[optind + 1]));
117 usage (EXIT_FAILURE);