OpenVPN 3 Core Library
Loading...
Searching...
No Matches
test_buffer_ip.cpp
Go to the documentation of this file.
1// Test fast BufferFormat::ipv4/ipv6.
2// Verify that formating exactly matches inet_ntop().
3
4#include <arpa/inet.h>
5
6#include "test_common.hpp"
7
11
12using namespace openvpn;
13
14static std::string to_hex(const std::uint32_t value)
15{
16 std::ostringstream os;
17 os << std::hex << value;
18 return os.str();
19}
20
21TEST(buffer_ip, unsigned_decimal)
22{
24 for (int i = -1000; i < 1000; ++i)
25 {
26 StaticBuffer<Decimal::max_length()> buf;
27 Decimal::write(buf, std::uint32_t(i));
28 ASSERT_EQ(buf_to_string(buf), std::to_string(std::uint32_t(i)));
29 }
30}
31
32TEST(buffer_ip, hex)
33{
35 for (int i = -1000; i < 1000; ++i)
36 {
38 Hex::write(buf, std::uint32_t(i));
39 ASSERT_EQ(buf_to_string(buf), to_hex(std::uint32_t(i)));
40 }
41}
42
43#ifdef INSTRUMENTATION_SLOWDOWN
44static constexpr int ITER = 10000;
45#else
46static constexpr int ITER = 1000000;
47#endif
48
49TEST(buffer_ip, ipv4)
50{
51 MTRand::Ptr prng(new MTRand());
52 for (int count = 0; count < ITER; ++count)
53 {
54 std::uint32_t addr;
55 prng->rand_fill(addr);
56
58 BufferFormat::ipv4(buf, addr);
59
60 char in_buffer[16];
61 if (::inet_ntop(AF_INET, &addr, in_buffer, sizeof(in_buffer)) == nullptr)
62 throw Exception("inet_ntop failed for IPv4");
63
64 ASSERT_EQ(std::string(in_buffer), buf_to_string(buf));
65 }
66}
67
68TEST(buffer_ip, ipv6)
69{
70 MTRand::Ptr prng(new MTRand());
71 for (int count = 0; count < ITER; ++count)
72 {
73 std::uint8_t addr[16];
74
75 switch (prng->randrange32(3))
76 {
77 case 0:
78 {
79 if (prng->randbool())
80 prng->rand_bytes(addr, sizeof(addr));
81 else
82 std::memset(addr, 0xff, sizeof(addr));
83
84 size_t start = prng->randrange32(16);
85 size_t end = prng->randrange32(16);
86 if (end < start)
87 std::swap(start, end);
88 if (prng->randbool())
89 {
90 for (size_t i = start; i < end; ++i)
91 addr[i] = 0;
92 }
93 else
94 {
95 for (size_t i = 0; i < 16; ++i)
96 if (i < start || i >= end)
97 addr[i] = 0;
98 }
99 }
100 break;
101 case 1:
102 for (size_t i = 0; i < 16; ++i)
103 addr[i] = prng->randbool() ? 0xff : 0;
104 break;
105 case 2:
106 prng->rand_bytes(addr, sizeof(addr));
107 break;
108 }
109
111 BufferFormat::ipv6(buf, addr);
112
113 char in_buffer[40];
114 if (::inet_ntop(AF_INET6, addr, in_buffer, sizeof(in_buffer)) == nullptr)
115 throw Exception("inet_ntop failed for IPv6");
116
117 ASSERT_EQ(std::string(in_buffer), buf_to_string(buf));
118 }
119}
The smart pointer class.
Definition rc.hpp:119
static void ipv6(Buffer &buf, const void *addr)
Definition bufip.hpp:36
static void ipv4(Buffer &buf, const std::uint32_t addr)
Definition bufip.hpp:23
std::string buf_to_string(const Buffer &buf)
Definition bufstr.hpp:22
static std::string to_hex(const std::uint32_t value)
static constexpr int ITER
TEST(buffer_ip, unsigned_decimal)
remote_address ipv6
reroute_gw ipv4
std::ostringstream os