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 throw ipv4_bad_prefix_len();
24}
25
26inline int prefix_len(const IPv4::Addr::base_type mask)
27{
28 if (mask != ~0U)
29 {
30 unsigned int high = 32;
31 unsigned int low = 1;
32 for (unsigned int i = 0; i < 5; ++i)
33 {
34 const unsigned int mid = (high + low) / 2;
36 if (mask == test)
37 return mid;
38 if (mask > test)
39 low = mid;
40 else
41 high = mid;
42 }
43 return -1;
44 }
45 return 32;
46}
47
48TEST(IPAddr, Test32)
49{
50 for (unsigned int i = 1; i <= 32; ++i)
51 {
53 const int pl = prefix_len(mask);
54 ASSERT_EQ(pl, (int)i);
55
56 // IPv4::Addr a = IPv4::Addr::from_uint32(mask);
57 // std::cout << i << ' ' << pl << ' ' << a << "\n";
58 }
59}
60
61TEST(IPAddr, Prefixlen)
62{
63 for (unsigned int i = 0; i <= 32; ++i)
64 {
66 const unsigned int pl = mask.prefix_len();
67 ASSERT_EQ(pl, i);
68 // std::cout << i << ' ' << pl << ' ' << mask << "\n";
69 }
70}
71
72void testbig() // exhaustive test of all 2^32 possible netmask values
73{
74 unsigned int mask = 0;
75 while (true)
76 {
77 const int pl = prefix_len(mask);
78 if (pl != -1)
79 std::cout << pl << ' ' << IPv4::Addr::from_uint32(mask) << '\n';
80 if (++mask == 0)
81 break;
82 }
83}
static Addr netmask_from_prefix_len(const unsigned int prefix_len)
Definition ipv4.hpp:186
unsigned int prefix_len() const
Definition ipv4.hpp:453
std::uint32_t base_type
Definition ipv4.hpp:45
static Addr from_uint32(const base_type addr)
Definition ipv4.hpp:97
#define OPENVPN_SIMPLE_EXCEPTION(C)
Definition exception.hpp:74
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()
TEST(IPAddr, Test32)
int prefix_len(const IPv4::Addr::base_type mask)
void test()
Definition test_rc.cpp:80