Import release 0.1.6
[secnet] / ipaddr.c
CommitLineData
7138d0c5
SE
1#include "secnet.h"
2#include <stdio.h>
3
4/* This file should eventually incorporate all the functionality of
5 ipaddr.py */
6
7bool_t subnet_match(struct subnet *s, uint32_t address)
8{
9 return (s->prefix==(address&s->mask));
10}
11
12bool_t subnet_matches_list(struct subnet_list *list, uint32_t address)
13{
14 uint32_t i;
15 for (i=0; i<list->entries; i++) {
16 if (list->list[i].prefix == (address&list->list[i].mask)) return True;
17 }
18 return False;
19}
20
21bool_t subnets_intersect(struct subnet a, struct subnet b)
22{
23 uint32_t mask=a.mask&b.mask;
24 return ((a.prefix&mask)==(b.prefix&mask));
25}
26
27bool_t subnet_intersects_with_list(struct subnet a, struct subnet_list *b)
28{
29 uint32_t i;
30
31 for (i=0; i<b->entries; i++) {
32 if (subnets_intersect(a,b->list[i])) return True;
33 }
34 return False;
35}
36
37bool_t subnet_lists_intersect(struct subnet_list *a, struct subnet_list *b)
38{
39 uint32_t i;
40 for (i=0; i<a->entries; i++) {
41 if (subnet_intersects_with_list(a->list[i],b)) return True;
42 }
43 return False;
44}
45
46/* The string buffer must be at least 16 bytes long */
47string_t ipaddr_to_string(uint32_t addr)
48{
49 uint8_t a,b,c,d;
50 string_t s;
51
52 s=safe_malloc(16,"ipaddr_to_string");
53 a=addr>>24;
54 b=addr>>16;
55 c=addr>>8;
56 d=addr;
57 snprintf(s, 16, "%d.%d.%d.%d", a, b, c, d);
58 return s;
59}
60
61string_t subnet_to_string(struct subnet *sn)
62{
63 uint32_t mask=sn->mask, addr=sn->prefix;
64 uint8_t a,b,c,d;
65 string_t s;
66 int i;
67
68 s=safe_malloc(19,"subnet_to_string");
69 a=addr>>24;
70 b=addr>>16;
71 c=addr>>8;
72 d=addr;
73 for (i=0; mask; i++) {
74 mask=(mask<<1);
75 }
76 if (i!=sn->len) {
77 fatal("subnet_to_string: invalid subnet structure!\n");
78 }
79 snprintf(s, 19, "%d.%d.%d.%d/%d", a, b, c, d, sn->len);
80 return s;
81}