1 /* Copyright (C) 1995-2015 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <http://www.gnu.org/licenses/>. */
23 #include <not-cancel.h>
25 #define HOSTIDFILE "/etc/hostid"
36 /* Test for appropriate rights to set host ID. */
37 if (__libc_enable_secure
)
43 /* Make sure the ID is not too large. Needed for bi-arch support. */
46 __set_errno (EOVERFLOW
);
50 /* Open file for writing. Everybody is allowed to read this file. */
51 fd
= open_not_cancel (HOSTIDFILE
, O_CREAT
|O_WRONLY
|O_TRUNC
, 0644);
55 written
= write_not_cancel (fd
, &id32
, sizeof (id32
));
57 close_not_cancel_no_status (fd
);
59 return written
!= sizeof (id32
) ? -1 : 0;
64 # include <sys/param.h>
65 # include <resolv/netdb.h>
66 # include <netinet/in.h>
71 char hostname
[MAXHOSTNAMELEN
+ 1];
74 struct hostent hostbuf
, *hp
;
80 /* First try to get the ID from a former invocation of sethostid. */
81 fd
= open_not_cancel (HOSTIDFILE
, O_RDONLY
|O_LARGEFILE
, 0);
84 ssize_t n
= read_not_cancel (fd
, &id
, sizeof (id
));
86 close_not_cancel_no_status (fd
);
92 /* Getting from the file was not successful. An intelligent guess for
93 a unique number of a host is its IP address. Return this. */
94 if (__gethostname (hostname
, MAXHOSTNAMELEN
) < 0 || hostname
[0] == '\0')
95 /* This also fails. Return and arbitrary value. */
99 buffer
= __alloca (buflen
);
101 /* To get the IP address we need to know the host name. */
102 while (__gethostbyname_r (hostname
, &hostbuf
, buffer
, buflen
, &hp
, &herr
)
105 if (herr
!= NETDB_INTERNAL
|| errno
!= ERANGE
)
108 /* Enlarge buffer. */
109 buffer
= extend_alloca (buffer
, buflen
, 2 * buflen
);
112 memcpy (&in
, hp
->h_addr
,
113 (int) sizeof (in
) < hp
->h_length
? (int) sizeof (in
) : hp
->h_length
);
115 /* For the return value to be not exactly the IP address we do some
117 return (int32_t) (in
.s_addr
<< 16 | in
.s_addr
>> 16);