system/hostname: Add an option to read the hostname from a file
* Private Data
****************************************************************************/
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: show_usage
+ ****************************************************************************/
+
+static void show_usage(FAR const char *progname)
+{
+ printf("Usage: %s [<hostname>|-F <file>]\n", progname);
+}
+
/****************************************************************************
* Public Functions
****************************************************************************/
int main(int argc, FAR char *argv[])
{
int ret;
- char hostname[HOST_NAME_MAX + 1];
+ bool set = false;
+ FAR FILE *f;
+ char hostname[HOST_NAME_MAX + 2];
+
+ while ((ret = getopt(argc, argv, ":F:h")) != ERROR)
+ {
+ switch (ret)
+ {
+ case 'F':
+ set = true;
+ f = fopen(optarg, "r");
+ if (f == NULL)
+ {
+ fprintf(stderr, "ERROR: Failed to open '%s': %s\n", optarg,
+ strerror(errno));
+ return EXIT_FAILURE;
+ }
+
+ if (fgets(hostname, sizeof(hostname), f) == NULL)
+ {
+ if (errno != 0)
+ {
+ fprintf(stderr, "ERROR: Failed to read '%s': %s\n",
+ optarg, strerror(errno));
+ fclose(f);
+ return EXIT_FAILURE;
+ }
- if (argc > 1)
+ hostname[0] = '\0';
+ }
+ else
+ {
+ *strchrnul(hostname, '\n') = '\0';
+ }
+
+ fclose(f);
+ break;
+
+ case 'h':
+ show_usage(argv[0]);
+ return EXIT_SUCCESS;
+
+ case ':':
+ fprintf(stderr, "ERROR: Option needs a value: '%c'\n", optopt);
+ show_usage(argv[0]);
+ return EXIT_FAILURE;
+
+ default:
+ case '?':
+ fprintf(stderr, "ERROR: Unrecognized option: '%c'\n", optopt);
+ show_usage(argv[0]);
+ return EXIT_FAILURE;
+ }
+ }
+
+ if (optind < argc && !set)
{
- if (argc > 2)
+ set = true;
+ strlcpy(hostname, argv[optind++], sizeof(hostname));
+ }
+
+ if (optind < argc)
{
fprintf(stderr, "ERROR: Too many arguments\n");
+ return -1;
+ }
+
+ if (set)
+ {
+ if (strlen(hostname) == 0 || strlen(hostname) > HOST_NAME_MAX)
+ {
+ fprintf(stderr, "ERROR: The specified hostname is invalid\n");
return EXIT_FAILURE;
}
- ret = sethostname(argv[1], strlen(argv[1]));
+ ret = sethostname(hostname, strlen(hostname));
if (ret != 0)
{
- printf("sethostname() returned %d\n", ret);
+ fprintf(stderr, "sethostname() returned %d\n", ret);
return EXIT_FAILURE;
}
}
@@ -64,7 +142,7 @@ int main(int argc, FAR char *argv[])
ret = gethostname(hostname, HOST_NAME_MAX);
if (ret != 0)
{
- printf("gethostname() returned %d\n", ret);
+ fprintf(stderr, "gethostname() returned %d\n", ret);
return EXIT_FAILURE;
}
