]> git.ipfire.org Git - people/ms/strongswan.git/blame - src/libfreeswan/libfreeswan/subnettypeof.c
- started to rebuild source layout
[people/ms/strongswan.git] / src / libfreeswan / libfreeswan / subnettypeof.c
CommitLineData
997358a6
MW
1/*
2 * extract parts of an ip_subnet, and related
3 * Copyright (C) 2000 Henry Spencer.
4 *
5 * This library is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU Library General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/lgpl.txt>.
9 *
10 * This library is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
13 * License for more details.
14 *
15 * RCSID $Id: subnettypeof.c,v 1.1 2004/03/15 20:35:26 as Exp $
16 */
17#include "internal.h"
18#include "freeswan.h"
19
20/*
21 - subnettypeof - get the address type of an ip_subnet
22 */
23int
24subnettypeof(src)
25const ip_subnet *src;
26{
27 return src->addr.u.v4.sin_family;
28}
29
30/*
31 - networkof - get the network address of a subnet
32 */
33void
34networkof(src, dst)
35const ip_subnet *src;
36ip_address *dst;
37{
38 *dst = src->addr;
39}
40
41/*
42 - maskof - get the mask of a subnet, as an address
43 */
44void
45maskof(src, dst)
46const ip_subnet *src;
47ip_address *dst;
48{
49 int b;
50 unsigned char buf[16];
51 size_t n = addrlenof(&src->addr);
52 unsigned char *p;
53
54 if (src->maskbits > n*8 || n > sizeof(buf))
55 return; /* "can't happen" */
56
57 p = buf;
58 for (b = src->maskbits; b >= 8; b -= 8)
59 *p++ = 0xff;
60 if (b != 0)
61 *p++ = (0xff << (8 - b)) & 0xff;
62 while (p - buf < n)
63 *p++ = 0;
64
65 (void) initaddr(buf, n, addrtypeof(&src->addr), dst);
66}
67
68/*
69 - masktocount - convert a mask, expressed as an address, to a bit count
70 */
71int /* -1 if not valid mask */
72masktocount(src)
73const ip_address *src;
74{
75 int b;
76 unsigned const char *bp;
77 size_t n;
78 unsigned const char *p;
79 unsigned const char *stop;
80
81 n = addrbytesptr(src, &bp);
82 if (n == 0)
83 return -1;
84
85 p = bp;
86 stop = bp + n;
87
88 n = 0;
89 while (p < stop && *p == 0xff) {
90 p++;
91 n += 8;
92 }
93 if (p < stop && *p != 0) { /* boundary in mid-byte */
94 b = *p++;
95 while (b&0x80) {
96 b <<= 1;
97 n++;
98 }
99 if ((b&0xff) != 0)
100 return -1; /* bits not contiguous */
101 }
102 while (p < stop && *p == 0)
103 p++;
104
105 if (p != stop)
106 return -1;
107
108 return n;
109}