hostid.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Copyright (C) 2000-2006 Erik Andersen <andersen@uclibc.org>
  4. *
  5. * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
  6. */
  7. #define __FORCE_GLIBC
  8. #include <features.h>
  9. #include <errno.h>
  10. #include <unistd.h>
  11. #include <sys/types.h>
  12. #include <fcntl.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <netdb.h>
  16. #define HOSTID "/etc/hostid"
  17. #ifdef __USE_BSD
  18. int sethostid(long int new_id)
  19. {
  20. int fd;
  21. int ret;
  22. if (geteuid() || getuid())
  23. return __set_errno(EPERM);
  24. fd = open(HOSTID, O_CREAT|O_WRONLY, 0644);
  25. if (fd < 0)
  26. return fd;
  27. ret = write(fd, &new_id, sizeof(new_id)) == sizeof(new_id) ? 0 : -1;
  28. close(fd);
  29. return ret;
  30. }
  31. #endif
  32. #define _addr(a) (((struct sockaddr_in*)a->ai_addr)->sin_addr.s_addr)
  33. long int gethostid(void)
  34. {
  35. char host[HOST_NAME_MAX + 1];
  36. int fd, id = 0;
  37. /* If hostid was already set then we can return that value.
  38. * It is not an error if we cannot read this file. It is not even an
  39. * error if we cannot read all the bytes, we just carry on trying...
  40. */
  41. fd = open(HOSTID, O_RDONLY);
  42. if (fd >= 0) {
  43. int i = read(fd, &id, sizeof(id));
  44. close(fd);
  45. if (i > 0)
  46. return id;
  47. }
  48. /* Try some methods of returning a unique 32 bit id. Clearly IP
  49. * numbers, if on the internet, will have a unique address. If they
  50. * are not on the internet then we can return 0 which means they should
  51. * really set this number via a sethostid() call. If their hostname
  52. * returns the loopback number (i.e. if they have put their hostname
  53. * in the /etc/hosts file with 127.0.0.1) then all such hosts will
  54. * have a non-unique hostid, but it doesn't matter anyway and
  55. * gethostid() will return a non zero number without the need for
  56. * setting one anyway.
  57. * Mitch
  58. */
  59. if (gethostname(host, HOST_NAME_MAX) >= 0 && *host) {
  60. struct addrinfo hints, *results, *addr;
  61. memset(&hints, 0, sizeof(struct addrinfo));
  62. if (!getaddrinfo(host, NULL, &hints, &results)) {
  63. for (addr = results; addr; addr = results->ai_next) {
  64. /* Just so it doesn't look exactly like the
  65. IP addr */
  66. id = _addr(addr) << 16 | _addr(addr) >> 16;
  67. break;
  68. }
  69. freeaddrinfo(results);
  70. }
  71. }
  72. return id;
  73. }