home *** CD-ROM | disk | FTP | other *** search
/ Serving the Web / ServingTheWeb1995.disc1of1.iso / linux / slacksrce / d / libc / libc-4.6 / libc-4 / libc-linux / misc / hostid.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-09-01  |  2.0 KB  |  74 lines

  1. #include <stdio.h>
  2. #include <errno.h>
  3. #include <sys/param.h>
  4. #include <netinet/in.h>
  5. #include <netdb.h>
  6. #include <fcntl.h>
  7. #include <unistd.h>
  8.  
  9.  
  10. #define HOSTID "/etc/hostid"
  11.  
  12. int sethostid(long int new_id)
  13. {
  14.     int fd;
  15.     int ret;
  16.  
  17.     if (geteuid() || getuid()) return errno=EPERM;
  18.     if ((fd=open(HOSTID,O_CREAT|O_WRONLY,0644))<0) return -1;
  19.     ret = write(fd,&new_id,sizeof(new_id)) == sizeof(new_id)
  20.         ? 0 : -1;
  21.     close (fd);
  22.     return ret;
  23. }
  24.  
  25. long int gethostid(void)
  26. {
  27.         char host[MAXHOSTNAMELEN + 1];
  28.     int fd, id;
  29.  
  30.     /* If hostid was already set the we can return that value.
  31.      * It is not an error if we cannot read this file. It is not even an
  32.      * error if we cannot read all the bytes, we just carry on trying...
  33.      */
  34.     if ((fd=open(HOSTID,O_RDONLY))>=0 && read(fd,&id,sizeof(id)))
  35.     {
  36.         close (fd);
  37.         return id;
  38.     }
  39.     if (fd >= 0) close (fd);
  40.  
  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.  
  56.         if ((hp = gethostbyname(host)) == (struct hostent *)NULL)
  57.  
  58.         /* This is not a error if we get here, as all it means is that
  59.          * this host is not on a network and/or they have not
  60.          * configured their network properly. So we return the unset
  61.          * hostid which should be 0, meaning that they should set it !!
  62.          */
  63.             return 0;
  64.         else {
  65.             memcpy((char *) &in, (char *) hp->h_addr, hp->h_length);
  66.  
  67.             /* Just so it doesn't look exactly like the IP addr */
  68.             return(in.s_addr<<16|in.s_addr>>16);
  69.         }
  70.     }
  71.     else return 0;
  72.  
  73. }
  74.