1 /* hostname - set or print the name of current host system
2 Copyright (C) 1994-2023 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 <https://www.gnu.org/licenses/>. */
17 /* Written by Jim Meyering. */
21 #include <sys/types.h>
24 #include "long-options.h"
26 #include "xgethostname.h"
28 /* The official name of this program (e.g., no 'g' prefix). */
29 #define PROGRAM_NAME "hostname"
31 #define AUTHORS proper_name ("Jim Meyering")
33 #ifndef HAVE_SETHOSTNAME
34 # if defined HAVE_SYSINFO && defined HAVE_SYS_SYSTEMINFO_H
35 # include <sys/systeminfo.h>
39 sethostname (char const *name
, size_t namelen
)
41 # if defined HAVE_SYSINFO && defined HAVE_SYS_SYSTEMINFO_H
42 /* Using sysinfo() is the SVR4 mechanism to set a hostname. */
43 return (sysinfo (SI_SET_HOSTNAME
, name
, namelen
) < 0 ? -1 : 0);
54 if (status
!= EXIT_SUCCESS
)
61 Print or set the hostname of the current system.\n\
64 program_name
, program_name
);
65 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
66 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
67 emit_ancillary_info (PROGRAM_NAME
);
73 main (int argc
, char **argv
)
77 initialize_main (&argc
, &argv
);
78 set_program_name (argv
[0]);
79 setlocale (LC_ALL
, "");
80 bindtextdomain (PACKAGE
, LOCALEDIR
);
83 atexit (close_stdout
);
85 parse_gnu_standard_options_only (argc
, argv
, PROGRAM_NAME
, PACKAGE_NAME
,
86 Version
, true, usage
, AUTHORS
,
87 (char const *) nullptr);
89 if (optind
+ 1 < argc
)
91 error (0, 0, _("extra operand %s"), quote (argv
[optind
+ 1]));
95 if (optind
+ 1 == argc
)
97 /* Set hostname to operand. */
98 char const *name
= argv
[optind
];
99 if (sethostname (name
, strlen (name
)) != 0)
100 error (EXIT_FAILURE
, errno
, _("cannot set name to %s"),
105 hostname
= xgethostname ();
106 if (hostname
== nullptr)
107 error (EXIT_FAILURE
, errno
, _("cannot determine hostname"));
111 main_exit (EXIT_SUCCESS
);