1 /* hostname - set or print the name of current host system
2 Copyright (C) 1994-1997, 1999-2005 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 2, or (at your option)
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, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* Written by Jim Meyering. */
23 #include <sys/types.h>
26 #include "long-options.h"
29 #include "xgethostname.h"
31 /* The official name of this program (e.g., no `g' prefix). */
32 #define PROGRAM_NAME "hostname"
34 #define AUTHORS "Jim Meyering"
36 #if HAVE_SETHOSTNAME && !defined sethostname
40 #if !defined HAVE_SETHOSTNAME && defined HAVE_SYSINFO && \
41 defined HAVE_SYS_SYSTEMINFO_H
42 # include <sys/systeminfo.h>
45 sethostname (char *name, size_t namelen)
47 /* Using sysinfo() is the SVR4 mechanism to set a hostname. */
48 return (sysinfo (SI_SET_HOSTNAME, name, namelen) < 0 ? -1 : 0);
51 # define HAVE_SETHOSTNAME 1 /* Now we have it... */
54 /* The name this program was run with. */
60 if (status != EXIT_SUCCESS)
61 fprintf (stderr, _("Try `%s --help' for more information.\n"),
68 Print or set the hostname of the current system.\n\
71 program_name, program_name);
72 fputs (HELP_OPTION_DESCRIPTION, stdout);
73 fputs (VERSION_OPTION_DESCRIPTION, stdout);
74 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
80 main (int argc, char **argv)
84 initialize_main (&argc, &argv);
85 program_name = argv[0];
86 setlocale (LC_ALL, "");
87 bindtextdomain (PACKAGE, LOCALEDIR);
90 atexit (close_stdout);
92 parse_long_options (argc, argv, PROGRAM_NAME, GNU_PACKAGE, VERSION,
93 usage, AUTHORS, (char const *) NULL);
94 if (getopt_long (argc, argv, "", NULL, NULL) != -1)
97 if (argc == optind + 1)
99 #ifdef HAVE_SETHOSTNAME
100 /* Set hostname to operand. */
101 char const *name = argv[optind];
102 if (sethostname (name, strlen (name)) != 0)
103 error (EXIT_FAILURE, errno, _("cannot set name to %s"), quote (name));
105 error (EXIT_FAILURE, 0,
106 _("cannot set hostname; this system lacks the functionality"));
112 hostname = xgethostname ();
113 if (hostname == NULL)
114 error (EXIT_FAILURE, errno, _("cannot determine hostname"));
115 printf ("%s\n", hostname);
118 if (optind + 1 < argc)
120 error (0, 0, _("extra operand %s"), quote (argv[optind + 1]));
121 usage (EXIT_FAILURE);