hostid.c 2.0 KB

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