diff --git a/coreutils/hostname.c b/coreutils/hostname.c new file mode 100644 index 0000000..dbd641e --- /dev/null +++ b/coreutils/hostname.c @@ -0,0 +1,80 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +int main(const int argc, const char **argv) { + unsigned int f_flag = 0; + unsigned int d_flag = 0; + unsigned int i_flag = 0; + + int i; + for (i = 1; i < argc; i++) { + if (argv[i][0] != '-') + break; + + else if (!strcmp(argv[i], "-f")) + f_flag = 1; + + else if (!strcmp(argv[i], "-d")) + d_flag = 1; + + else if (!strcmp(argv[i], "-i")) + i_flag = 1; + + else if (!strcmp(argv[i], "--help")) { + printf("hostname [-f (Display the FQDN)] [-d (Display domainname)] [-i (Addresses for the hostname)]/ [hostname (Set new hostname)]\n"); + return 0; + } + } + + + /* Set hostname */ + if (argc - i == 1) { + if (sethostname(argv[argc - 1], strlen(argv[argc - 1])) < 0) { + fprintf(stderr, "hostname: %s\n", strerror(errno)); + return 1; + } + + return 0; + } + + /* Get info */ + char hostname[HOST_NAME_MAX]; + if (gethostname(hostname, sizeof(hostname)) < 0) { + fprintf(stderr, "hostname: %s\n", strerror(errno)); + return 1; + } + + + struct hostent *hp = gethostbyname(hostname); + if (!hp) { + fprintf(stderr, "hostname: %s\n", strerror(errno)); + return 1; + } + + /* Print info */ + if (f_flag) + puts(hp->h_name); + + else if (d_flag) { + char *ptr = strchr(hp->h_name, '.'); + if (ptr) + puts(ptr + 1); + } + + else if (i_flag) { + while (hp->h_addr_list[0]) + printf("%s ", inet_ntoa( *(struct in_addr *) *(hp->h_addr_list++) )); + printf("\n"); + } + + else + puts(hostname); + + return 0; +}