1 /* hostname - set or print the name of current host system
2 Copyright (C) 1994-1997, 1999-2005, 2007-2011 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 !defined HAVE_SETHOSTNAME && defined HAVE_SYSINFO && \
36 defined HAVE_SYS_SYSTEMINFO_H
37 # include <sys/systeminfo.h>
40 sethostname (char *name
, size_t namelen
)
42 /* Using sysinfo() is the SVR4 mechanism to set a hostname. */
43 return (sysinfo (SI_SET_HOSTNAME
, name
, namelen
) < 0 ? -1 : 0);
46 # define HAVE_SETHOSTNAME 1 /* Now we have it... */
52 if (status
!= EXIT_SUCCESS
)
53 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
60 Print or set the hostname of the current system.\n\
63 program_name
, program_name
);
64 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
65 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
66 emit_ancillary_info ();
72 main (int argc
, char **argv
)
76 initialize_main (&argc
, &argv
);
77 set_program_name (argv
[0]);
78 setlocale (LC_ALL
, "");
79 bindtextdomain (PACKAGE
, LOCALEDIR
);
82 atexit (close_stdout
);
84 parse_long_options (argc
, argv
, PROGRAM_NAME
, PACKAGE_NAME
, Version
,
85 usage
, AUTHORS
, (char const *) NULL
);
86 if (getopt_long (argc
, argv
, "", NULL
, NULL
) != -1)
89 if (argc
== optind
+ 1)
91 #ifdef HAVE_SETHOSTNAME
92 /* Set hostname to operand. */
93 char const *name
= argv
[optind
];
94 if (sethostname (name
, strlen (name
)) != 0)
95 error (EXIT_FAILURE
, errno
, _("cannot set name to %s"), quote (name
));
97 error (EXIT_FAILURE
, 0,
98 _("cannot set hostname; this system lacks the functionality"));
104 hostname
= xgethostname ();
105 if (hostname
== NULL
)
106 error (EXIT_FAILURE
, errno
, _("cannot determine hostname"));
107 printf ("%s\n", hostname
);
110 if (optind
+ 1 < argc
)
112 error (0, 0, _("extra operand %s"), quote (argv
[optind
+ 1]));
113 usage (EXIT_FAILURE
);