remove libintl stub and libintl.h header
[uclibc-ng.git] / libc / inet / hostid.c
blobd05a84f687e954f0effa71d2c867af743c59a912
1 /* vi: set sw=4 ts=4: */
2 /*
3 * Copyright (C) 2000-2006 Erik Andersen <andersen@uclibc.org>
5 * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
6 */
8 #include <errno.h>
9 #include <unistd.h>
10 #include <sys/types.h>
11 #include <fcntl.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <netdb.h>
15 #include <not-cancel.h>
17 #define HOSTID "/etc/hostid"
19 #ifdef __USE_BSD
20 int sethostid(long int new_id)
22 int fd;
23 int ret;
25 if (geteuid() || getuid())
26 return __set_errno(EPERM);
27 fd = open_not_cancel(HOSTID, O_CREAT|O_WRONLY, 0644);
28 if (fd < 0)
29 return fd;
30 ret = write_not_cancel(fd, &new_id, sizeof(new_id)) == sizeof(new_id) ? 0 : -1;
31 close_not_cancel_no_status (fd);
32 return ret;
34 #endif
36 #define _addr(a) (((struct sockaddr_in*)a->ai_addr)->sin_addr.s_addr)
37 long int gethostid(void)
39 char host[HOST_NAME_MAX + 1];
40 int fd, id = 0;
42 /* If hostid was already set then we can return that value.
43 * It is not an error if we cannot read this file. It is not even an
44 * error if we cannot read all the bytes, we just carry on trying...
46 fd = open_not_cancel_2(HOSTID, O_RDONLY);
47 if (fd >= 0) {
48 int i = read_not_cancel(fd, &id, sizeof(id));
49 close_not_cancel_no_status(fd);
50 if (i > 0)
51 return id;
53 /* Try some methods of returning a unique 32 bit id. Clearly IP
54 * numbers, if on the internet, will have a unique address. If they
55 * are not on the internet then we can return 0 which means they should
56 * really set this number via a sethostid() call. If their hostname
57 * returns the loopback number (i.e. if they have put their hostname
58 * in the /etc/hosts file with 127.0.0.1) then all such hosts will
59 * have a non-unique hostid, but it doesn't matter anyway and
60 * gethostid() will return a non zero number without the need for
61 * setting one anyway.
62 * Mitch
64 if (gethostname(host, HOST_NAME_MAX) >= 0 && *host) {
65 struct addrinfo hints, *results, *addr;
66 memset(&hints, 0, sizeof(struct addrinfo));
67 if (!getaddrinfo(host, NULL, &hints, &results)) {
68 for (addr = results; addr; addr = results->ai_next) {
69 /* Just so it doesn't look exactly like the
70 IP addr */
71 id = _addr(addr) << 16 | _addr(addr) >> 16;
72 break;
74 freeaddrinfo(results);
77 return id;