hostname.c 837 B

12345678910111213141516171819202122232425262728293031323334353637
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2013-2018 K. Lange
  5. *
  6. * hostname
  7. *
  8. * Prints or sets the system hostname.
  9. */
  10. #include <stdio.h>
  11. #include <unistd.h>
  12. #include <string.h>
  13. int main(int argc, char * argv[]) {
  14. if ((argc > 1 && argv[1][0] == '-') || (argc < 2)) {
  15. char tmp[256] = {0};
  16. gethostname(tmp, 255);
  17. printf("%s\n", tmp);
  18. return 0;
  19. } else {
  20. if (geteuid() != 0) {
  21. fprintf(stderr,"Must be root to set hostname.\n");
  22. return 1;
  23. } else {
  24. sethostname(argv[1], strlen(argv[1]));
  25. FILE * file = fopen("/etc/hostname", "w");
  26. if (!file) {
  27. return 1;
  28. } else {
  29. fprintf(file, "%s\n", argv[1]);
  30. fclose(file);
  31. return 0;
  32. }
  33. }
  34. }
  35. return 0;
  36. }