hostid.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #define geteuid __geteuid
  2. #define getuid __getuid
  3. #define gethostbyname __gethostbyname
  4. #define gethostname __gethostname
  5. #define __FORCE_GLIBC
  6. #include <features.h>
  7. #include <stdio.h>
  8. #include <string.h>
  9. #include <errno.h>
  10. #include <sys/param.h>
  11. #include <netinet/in.h>
  12. #include <netdb.h>
  13. #include <fcntl.h>
  14. #include <unistd.h>
  15. #define HOSTID "/etc/hostid"
  16. int sethostid(long int new_id)
  17. {
  18. int fd;
  19. int ret;
  20. if (geteuid() || getuid()) return __set_errno(EPERM);
  21. if ((fd=__open(HOSTID,O_CREAT|O_WRONLY,0644))<0) return -1;
  22. ret = __write(fd,(void *)&new_id,sizeof(new_id)) == sizeof(new_id)
  23. ? 0 : -1;
  24. __close (fd);
  25. return ret;
  26. }
  27. long int gethostid(void)
  28. {
  29. char host[MAXHOSTNAMELEN + 1];
  30. int fd, id;
  31. /* If hostid was already set the we can return that value.
  32. * It is not an error if we cannot read this file. It is not even an
  33. * error if we cannot read all the bytes, we just carry on trying...
  34. */
  35. if ((fd=__open(HOSTID,O_RDONLY))>=0 && __read(fd,(void *)&id,sizeof(id)))
  36. {
  37. __close (fd);
  38. return id;
  39. }
  40. if (fd >= 0) __close (fd);
  41. /* Try some methods of returning a unique 32 bit id. Clearly IP
  42. * numbers, if on the internet, will have a unique address. If they
  43. * are not on the internet then we can return 0 which means they should
  44. * really set this number via a sethostid() call. If their hostname
  45. * returns the loopback number (i.e. if they have put their hostname
  46. * in the /etc/hosts file with 127.0.0.1) then all such hosts will
  47. * have a non-unique hostid, but it doesn't matter anyway and
  48. * gethostid() will return a non zero number without the need for
  49. * setting one anyway.
  50. * Mitch
  51. */
  52. if (gethostname(host,MAXHOSTNAMELEN)>=0 && *host) {
  53. struct hostent *hp;
  54. struct in_addr in;
  55. if ((hp = gethostbyname(host)) == (struct hostent *)NULL)
  56. /* This is not a error if we get here, as all it means is that
  57. * this host is not on a network and/or they have not
  58. * configured their network properly. So we return the unset
  59. * hostid which should be 0, meaning that they should set it !!
  60. */
  61. return 0;
  62. else {
  63. __memcpy((char *) &in, (char *) hp->h_addr, hp->h_length);
  64. /* Just so it doesn't look exactly like the IP addr */
  65. return(in.s_addr<<16|in.s_addr>>16);
  66. }
  67. }
  68. else return 0;
  69. }