Tue Jul 9 09:37:55 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu>
[glibc.git] / sysdeps / unix / sysv / linux / gethostid.c
blob2883441c5bc0d29e35aac1066b447163a3eea503
1 /* Copyright (C) 1995, 1996 Free Software Foundation, Inc.
3 The GNU C Library is free software; you can redistribute it and/or
4 modify it under the terms of the GNU Library General Public License as
5 published by the Free Software Foundation; either version 2 of the
6 License, or (at your option) any later version.
8 The GNU C Library is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 Library General Public License for more details.
13 You should have received a copy of the GNU Library General Public
14 License along with the GNU C Library; see the file COPYING.LIB. If
15 not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 Boston, MA 02111-1307, USA. */
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <unistd.h>
22 #define HOSTIDFILE "/var/adm/hostid"
24 #ifdef SET_PROCEDURE
25 int
26 sethostid (id)
27 long int id;
29 int fd;
30 ssize_t written;
32 /* Test for appropriate rights to set host ID. */
33 if (geteuid () || getuid ())
35 errno = EPERM;
36 return -1;
39 /* Open file for writing. Everybody is allowed to read this file. */
40 fd = __open (HOSTIDFILE, O_CREAT|O_WRONLY, 0644);
41 if (fd < 0)
42 return -1;
44 written = __write (fd, &id, sizeof (id));
46 __close (fd);
48 return written != sizeof (id) ? -1 : 0;
51 #else
52 # include <string.h>
53 # include <sys/param.h>
54 # include <resolv/netdb.h>
55 # include <netinet/in.h>
57 long int
58 gethostid ()
60 char hostname[MAXHOSTNAMELEN + 1];
61 struct hostent *hp;
62 unsigned long id;
63 struct in_addr in;
64 int fd;
66 /* First try to get the ID from a former invocation of sethostid. */
67 fd = __open (HOSTIDFILE, O_RDONLY);
68 if (fd >= 0)
70 ssize_t n = __read (fd, &id, sizeof (id));
72 __close (fd);
74 if (n == sizeof (id))
75 return id;
78 /* Getting from the file was not succesful. An intelligent guess for
79 a unique number of a host is its IP address. Return this. */
80 if (gethostname (hostname, MAXHOSTNAMELEN) < 0 || hostname[0] == '\0')
81 /* This also fails. Return and arbitrary value. */
82 return 0;
84 /* To get the IP address we need to know the host name. */
85 hp = gethostbyname (hostname);
86 if (hp == NULL)
87 return 0;
89 in.s_addr = 0;
90 memcpy (&in, hp->h_addr,
91 (int) sizeof (in) < hp->h_length ? sizeof (in) : hp->h_length);
93 /* For the return value to be not exactly the IP address we do some
94 bit fiddling. */
95 return in.s_addr << 16 | in.s_addr >> 16;
97 #endif