aboutsummaryrefslogtreecommitdiffstats
path: root/src/libfreeswan/libfreeswan/subnettypeof.c
blob: 6f44b2e4b4ee130424676ce75b5c9bb5a9aeca25 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
 * extract parts of an ip_subnet, and related
 * Copyright (C) 2000  Henry Spencer.
 * 
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Library General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.  See <http://www.fsf.org/copyleft/lgpl.txt>.
 * 
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
 * License for more details.
 *
 * RCSID $Id: subnettypeof.c,v 1.1 2004/03/15 20:35:26 as Exp $
 */
#include "internal.h"
#include "freeswan.h"

/*
 - subnettypeof - get the address type of an ip_subnet
 */
int
subnettypeof(src)
const ip_subnet *src;
{
	return src->addr.u.v4.sin_family;
}

/*
 - networkof - get the network address of a subnet
 */
void
networkof(src, dst)
const ip_subnet *src;
ip_address *dst;
{
	*dst = src->addr;
}

/*
 - maskof - get the mask of a subnet, as an address
 */
void
maskof(src, dst)
const ip_subnet *src;
ip_address *dst;
{
	int b;
	unsigned char buf[16];
	size_t n = addrlenof(&src->addr);
	unsigned char *p;

	if (src->maskbits > n*8 || n > sizeof(buf))
		return;		/* "can't happen" */

	p = buf;
	for (b = src->maskbits; b >= 8; b -= 8)
		*p++ = 0xff;
	if (b != 0)
		*p++ = (0xff << (8 - b)) & 0xff;
	while (p - buf < n)
		*p++ = 0;

	(void) initaddr(buf, n, addrtypeof(&src->addr), dst);
}

/*
 - masktocount - convert a mask, expressed as an address, to a bit count
 */
int				/* -1 if not valid mask */
masktocount(src)
const ip_address *src;
{
	int b;
	unsigned const char *bp;
	size_t n;
	unsigned const char *p;
	unsigned const char *stop;

	n = addrbytesptr(src, &bp);
	if (n == 0)
		return -1;

	p = bp;
	stop = bp + n;

	n = 0;
	while (p < stop && *p == 0xff) {
		p++;
		n += 8;
	}
	if (p < stop && *p != 0) {	/* boundary in mid-byte */
		b = *p++;
		while (b&0x80) {
			b <<= 1;
			n++;
		}
		if ((b&0xff) != 0)
			return -1;	/* bits not contiguous */
	}
	while (p < stop && *p == 0)
		p++;

	if (p != stop)
		return -1;

	return n;
}