Fix up includes in html.c
[darkstat] / addr.c
1 /* darkstat 3
2 * copyright (c) 2011 Emil Mikulic.
3 *
4 * addr.c: compound IPv4/IPv6 address
5 *
6 * You may use, modify and redistribute this file under the terms of the
7 * GNU General Public License version 2. (see COPYING.GPL)
8 */
9
10 #include "addr.h"
11
12 #include <assert.h>
13 #include <string.h> /* for memcmp */
14 #include <netdb.h> /* for getaddrinfo */
15
16 int addr_equal(const struct addr * const a, const struct addr * const b)
17 {
18 if (a->family != b->family)
19 return 0;
20 if (a->family == IPv4)
21 return (a->ip.v4 == b->ip.v4);
22 else {
23 assert(a->family == IPv6);
24 return (memcmp(&(a->ip.v6), &(b->ip.v6), sizeof(a->ip.v6)) == 0);
25 }
26 }
27
28 static char _addrstrbuf[INET6_ADDRSTRLEN];
29 const char *addr_to_str(const struct addr * const a)
30 {
31 if (a->family == IPv4) {
32 struct in_addr in;
33 in.s_addr = a->ip.v4;
34 return (inet_ntoa(in));
35 } else {
36 assert(a->family == IPv6);
37 inet_ntop(AF_INET6, &(a->ip.v6), _addrstrbuf, sizeof(_addrstrbuf));
38 return (_addrstrbuf);
39 }
40 }
41
42 int str_to_addr(const char *s, struct addr *a)
43 {
44 struct addrinfo hints, *ai;
45 int ret;
46
47 memset(&hints, 0, sizeof(hints));
48 hints.ai_family = AF_UNSPEC;
49 hints.ai_flags = AI_NUMERICHOST;
50
51 if ((ret = getaddrinfo(s, NULL, &hints, &ai)) != 0)
52 return (ret);
53
54 if (ai->ai_family == AF_INET) {
55 a->family = IPv4;
56 a->ip.v4 = ((const struct sockaddr_in *)ai->ai_addr)->sin_addr.s_addr;
57 } else if (ai->ai_family == AF_INET6) {
58 a->family = IPv6;
59 memcpy(&(a->ip.v6),
60 ((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr.s6_addr,
61 sizeof(a->ip.v6));
62 } else {
63 ret = EAI_FAMILY;
64 }
65
66 freeaddrinfo(ai);
67 return (ret);
68 }
69
70 void addr_mask(struct addr *a, const struct addr * const mask)
71 {
72 assert(a->family == mask->family);
73 if (a->family == IPv4)
74 a->ip.v4 &= mask->ip.v4;
75 else {
76 size_t i;
77
78 assert(a->family == IPv6);
79 for (i=0; i<sizeof(a->ip.v6.s6_addr); i++)
80 a->ip.v6.s6_addr[i] &= mask->ip.v6.s6_addr[i];
81 }
82 }
83
84 int addr_inside(const struct addr * const a,
85 const struct addr * const net, const struct addr * const mask)
86 {
87 struct addr masked;
88
89 assert(a->family == net->family);
90 assert(a->family == mask->family);
91
92 masked = *a;
93 addr_mask(&masked, mask);
94 return (addr_equal(&masked, net));
95 }
96
97 /* vim:set ts=3 sw=3 tw=78 et: */