75 lines
1.3 KiB
C
75 lines
1.3 KiB
C
#include <stdio.h>
|
|
#include <errno.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <limits.h>
|
|
#include <unistd.h>
|
|
|
|
static void readcfg(const char *cfg, char *buf, size_t len) {
|
|
FILE *fp = fopen(cfg, "r");
|
|
if (fp == NULL) {
|
|
fprintf(stderr, "hostname: %s\n", strerror(errno));
|
|
exit(1);
|
|
}
|
|
|
|
if (fgets(buf, len, fp) == NULL) {
|
|
fprintf(stderr, "hostname: fgets returned NULL: %s\n", strerror(errno));
|
|
|
|
fclose(fp);
|
|
exit(1);
|
|
}
|
|
|
|
/* Remove \n from string */
|
|
*(strrchr(buf, '\n')) = '\0';
|
|
|
|
fclose(fp);
|
|
}
|
|
|
|
int main(int argc, char **argv) {
|
|
char hostname[HOST_NAME_MAX + 1];
|
|
char *newhost = NULL;
|
|
int config = 0;
|
|
|
|
int opt;
|
|
while ((opt = getopt(argc, argv, "c:F:")) != -1) {
|
|
switch (opt) {
|
|
case 'F':
|
|
case 'c':
|
|
readcfg(optarg, hostname, sizeof(hostname));
|
|
|
|
config = 1;
|
|
newhost = hostname;
|
|
break;
|
|
|
|
default:
|
|
printf("hostname [cF] [hostname]\n\t-c/-F PATH Use config file\n");
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
argc -= optind;
|
|
argv += optind;
|
|
|
|
if (newhost == NULL)
|
|
newhost = argv[0];
|
|
|
|
/* Set hostname */
|
|
if (argc == 1 || config) {
|
|
if (sethostname(newhost, strlen(newhost)) < 0) {
|
|
fprintf(stderr, "hostname: %s\n", strerror(errno));
|
|
return 1;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
/* Get hostname */
|
|
if (gethostname(hostname, sizeof(hostname)) < 0) {
|
|
fprintf(stderr, "hostname: %s\n", strerror(errno));
|
|
return 1;
|
|
}
|
|
|
|
puts(hostname);
|
|
return 0;
|
|
}
|