]> git.ipfire.org Git - thirdparty/coreutils.git/commitdiff
hostname: simplify
authorPaul Eggert <eggert@cs.ucla.edu>
Mon, 31 Jan 2022 16:42:07 +0000 (08:42 -0800)
committerPaul Eggert <eggert@cs.ucla.edu>
Mon, 31 Jan 2022 20:07:39 +0000 (12:07 -0800)
* src/hostname.c (sethostname): Provide a substitute on all
platforms, to simplify the mainline code.
(main): Simplify.  Remove an IF_LINT.
Use main_exit rather than return.

src/hostname.c

index 69e38bb373f086948150fb7c2eabfa52e6a021cf..e07e98b2b1555c3f309e442a7b553937a662248e 100644 (file)
 
 #define AUTHORS proper_name ("Jim Meyering")
 
-#if !defined HAVE_SETHOSTNAME && defined HAVE_SYSINFO && \
-     defined HAVE_SYS_SYSTEMINFO_H
-# include <sys/systeminfo.h>
+#ifndef HAVE_SETHOSTNAME
+# if defined HAVE_SYSINFO && defined HAVE_SYS_SYSTEMINFO_H
+#  include <sys/systeminfo.h>
+# endif
 
 static int
-sethostname (char *name, size_t namelen)
+sethostname (char const *name, size_t namelen)
 {
+# if defined HAVE_SYSINFO && defined HAVE_SYS_SYSTEMINFO_H
   /* Using sysinfo() is the SVR4 mechanism to set a hostname. */
   return (sysinfo (SI_SET_HOSTNAME, name, namelen) < 0 ? -1 : 0);
+# else
+  errno = ENOTSUP;
+  return -1;
+# endif
 }
-
-# define HAVE_SETHOSTNAME 1  /* Now we have it... */
 #endif
 
 void
@@ -84,34 +88,27 @@ main (int argc, char **argv)
                                    Version, true, usage, AUTHORS,
                                    (char const *) NULL);
 
-  if (argc == optind + 1)
+  if (optind + 1 < argc)
+     {
+       error (0, 0, _("extra operand %s"), quote (argv[optind + 1]));
+       usage (EXIT_FAILURE);
+     }
+
+  if (optind + 1 == argc)
     {
-#ifdef HAVE_SETHOSTNAME
       /* Set hostname to operand.  */
       char const *name = argv[optind];
       if (sethostname (name, strlen (name)) != 0)
         die (EXIT_FAILURE, errno, _("cannot set name to %s"),
              quote (name));
-#else
-      die (EXIT_FAILURE, 0,
-           _("cannot set hostname; this system lacks the functionality"));
-#endif
     }
-
-  if (argc <= optind)
+  else
     {
       hostname = xgethostname ();
       if (hostname == NULL)
         die (EXIT_FAILURE, errno, _("cannot determine hostname"));
       puts (hostname);
-      IF_LINT (free (hostname));
-    }
-
-  if (optind + 1 < argc)
-    {
-      error (0, 0, _("extra operand %s"), quote (argv[optind + 1]));
-      usage (EXIT_FAILURE);
     }
 
-  return EXIT_SUCCESS;
+  main_exit (EXIT_SUCCESS);
 }