src/world/bin/hostname/src/hostname.c

83 lines
2.4 KiB
C

/*
*----------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <jeang3nie@HitchHiker-Linux.org> wrote this file. As long as you
* retain this notice you can do whatever you want with this stuff. If
* we meet some day, and you think this stuff is worth it, you can buy
* me a beer in return.
* ---------------------------------------------------------------------
* ______ _______ _ _________
* ( __ \ ( ___ )( ( /|( )\__ __/
* | ( \ )| ( ) || \ ( ||/ ) (
* | | ) || | | || \ | | | |
* | | | || | | || (\ \) | | |
* | | ) || | | || | \ | | |
* | (__/ )| (___) || ) \ | | |
* (______/ (_______)|/ )_) )_(
*
* _______ _______ _ _________ _______
* ( ____ )( ___ )( \ /|\__ __/( ____ \
* | ( )|| ( ) || \ ( | ) ( | ( |/
* | (____)|| (___) || \ | | | | | |
* | _____)| ___ || (\ \) | | | | |
* | ( | ( ) || | \ | | | | |
* | ) | ) ( || ) \ |___) (___| (____|\
* |/ |/ \||/ \_)\_______/(_______/
*
*/
#define _DEFAULT_SOURCE
#include <sys/param.h> // HOST_NAME_MAX
#include <libgen.h> // basename
#include <stdio.h> // printf, fprintf
#include <stdlib.h> // exit
#include <string.h> // strlen
#include <unistd.h> // gethostname, sethostname, getopt
static const char *__progname;
static void usage() {
fprintf(stderr,
"Usage: %s [-s] [name-of-host]\n", __progname);
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[]) {
__progname = basename(argv[0]);
if (argc > 2)
usage();
int c, sflag = 0;
while ((c = getopt(argc, argv, "s")) != -1)
switch (c) {
case 's':
sflag = 1;
break;
case '?':
default:
usage();
}
if (argv[optind] != NULL) {
char * hostname[HOST_NAME_MAX];
*hostname = argv[optind];
if (sethostname(*hostname, strlen(*hostname)) != 0) {
perror("sethostname");
exit(EXIT_FAILURE);
}
} else {
char hostname[HOST_NAME_MAX + 1];
if (gethostname(hostname, sizeof(hostname)) != 0) {
perror("gethostname");
exit(EXIT_FAILURE);
}
if (!sflag) {
puts(hostname);
} else {
char * val = strtok(hostname, ".");
puts(val);
}
}
return 0;
}