add ipv6 support
[project/mdnsd.git] / util.c
1 /*
2  * Copyright (C) 2014 John Crispin <blogic@openwrt.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License version 2.1
6  * as published by the Free Software Foundation
7  *
8  * This program 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
11  * GNU General Public License for more details.
12  */
13
14 #include <sys/socket.h>
15 #include <sys/ioctl.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <sys/utsname.h>
19 #include <arpa/inet.h>
20
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <stdlib.h>
27 #include <signal.h>
28
29 #include <libubox/uloop.h>
30
31 #include "dns.h"
32 #include "util.h"
33
34 uint8_t mdns_buf[MDNS_BUF_LEN];
35 int debug = 0;
36
37 char mdns_hostname[HOSTNAME_LEN];
38 char mdns_hostname_local[HOSTNAME_LEN + 6];
39
40 uint32_t
41 rand_time_delta(uint32_t t)
42 {
43         uint32_t val;
44         int fd = open("/dev/urandom", O_RDONLY);
45
46         if (!fd)
47                 return t;
48
49         if (read(fd, &val, sizeof(val)) == sizeof(val)) {
50                 int range = t / 30;
51
52                 srand(val);
53                 val = t + (rand() % range) - (range / 2);
54         } else {
55                 val = t;
56         }
57
58         close(fd);
59
60         return val;
61 }
62
63 void get_hostname(void)
64 {
65         struct utsname utsname;
66
67         mdns_hostname[0] = 0;
68         mdns_hostname_local[0] = 0;
69
70         if (uname(&utsname) < 0)
71                 return;
72
73         snprintf(mdns_hostname, sizeof(mdns_hostname), "%s", utsname.nodename);
74         snprintf(mdns_hostname_local, sizeof(mdns_hostname_local), "%s.local", utsname.nodename);
75 }