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"
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 #ifndef HAVE_SETHOSTNAME
36 # if defined HAVE_SYSINFO && defined HAVE_SYS_SYSTEMINFO_H
37 # include <sys/systeminfo.h>
41 sethostname (char const *name
, size_t namelen
)
43 # if defined HAVE_SYSINFO && defined HAVE_SYS_SYSTEMINFO_H
44 /* Using sysinfo() is the SVR4 mechanism to set a hostname. */
45 return (sysinfo (SI_SET_HOSTNAME
, name
, namelen
) < 0 ? -1 : 0);
56 if (status
!= EXIT_SUCCESS
)
63 Print or set the hostname of the current system.\n\
66 program_name
, program_name
);
67 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
68 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
69 emit_ancillary_info (PROGRAM_NAME
);
75 main (int argc
, char **argv
)
79 initialize_main (&argc
, &argv
);
80 set_program_name (argv
[0]);
81 setlocale (LC_ALL
, "");
82 bindtextdomain (PACKAGE
, LOCALEDIR
);
85 atexit (close_stdout
);
87 parse_gnu_standard_options_only (argc
, argv
, PROGRAM_NAME
, PACKAGE_NAME
,
88 Version
, true, usage
, AUTHORS
,
91 if (optind
+ 1 < argc
)
93 error (0, 0, _("extra operand %s"), quote (argv
[optind
+ 1]));
97 if (optind
+ 1 == argc
)
99 /* Set hostname to operand. */
100 char const *name
= argv
[optind
];
101 if (sethostname (name
, strlen (name
)) != 0)
102 die (EXIT_FAILURE
, errno
, _("cannot set name to %s"),
107 hostname
= xgethostname ();
108 if (hostname
== NULL
)
109 die (EXIT_FAILURE
, errno
, _("cannot determine hostname"));
113 main_exit (EXIT_SUCCESS
);