OpenVPN 3 Core Library
Loading...
Searching...
No Matches
test_prefixlen.cpp
Go to the documentation of this file.
1#include "test_common.hpp"
2#include <iostream>
3#include <string>
4
6
7#include <openvpn/addr/ip.hpp>
8
9using namespace openvpn;
10
11OPENVPN_SIMPLE_EXCEPTION(ipv4_bad_prefix_len);
12OPENVPN_SIMPLE_EXCEPTION(ipv4_bad_netmask);
13
15{
16 return ~((1u << (32 - prefix_len)) - 1);
17}
18
20{
21 if (prefix_len >= 1 && prefix_len <= 32)
23 else
24 throw ipv4_bad_prefix_len();
25}
26
27inline int prefix_len(const IPv4::Addr::base_type mask)
28{
29 if (mask != ~0u)
30 {
31 unsigned int high = 32;
32 unsigned int low = 1;
33 for (unsigned int i = 0; i < 5; ++i)
34 {
35 const unsigned int mid = (high + low) / 2;
37 if (mask == test)
38 return mid;
39 else if (mask > test)
40 low = mid;
41 else
42 high = mid;
43 }
44 return -1;
45 }
46 else
47 return 32;
48}
49
50TEST(IPAddr, test32)
51{
52 for (unsigned int i = 1; i <= 32; ++i)
53 {
55 const int pl = prefix_len(mask);
56 ASSERT_EQ(pl, (int)i);
57
58 // IPv4::Addr a = IPv4::Addr::from_uint32(mask);
59 // std::cout << i << ' ' << pl << ' ' << a << std::endl;
60 }
61}
62
63TEST(IPAddr, prefixlen)
64{
65 for (unsigned int i = 0; i <= 32; ++i)
66 {
68 const unsigned int pl = mask.prefix_len();
69 ASSERT_EQ(pl, i);
70 // std::cout << i << ' ' << pl << ' ' << mask << std::endl;
71 }
72}
73
74void testbig() // exhaustive test of all 2^32 possible netmask values
75{
76 unsigned int mask = 0;
77 while (true)
78 {
79 const int pl = prefix_len(mask);
80 if (pl != -1)
81 std::cout << pl << ' ' << IPv4::Addr::from_uint32(mask) << std::endl;
82 if (++mask == 0)
83 break;
84 }
85}
static Addr netmask_from_prefix_len(const unsigned int prefix_len)
Definition ipv4.hpp:189
unsigned int prefix_len() const
Definition ipv4.hpp:456
std::uint32_t base_type
Definition ipv4.hpp:48
static Addr from_uint32(const base_type addr)
Definition ipv4.hpp:100
#define OPENVPN_SIMPLE_EXCEPTION(C)
Definition exception.hpp:75
IPv4::Addr::base_type prefix_len_to_netmask(const unsigned int prefix_len)
IPv4::Addr::base_type prefix_len_to_netmask_unchecked(const unsigned int prefix_len)
void testbig()
int prefix_len(const IPv4::Addr::base_type mask)
TEST(IPAddr, test32)
void test()
Definition test_rc.cpp:80