Botan 3.14.1
Crypto and TLS for C&
ipv4_address.cpp
Go to the documentation of this file.
1/*
2* (C) 2026 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#include <botan/ipv4_address.h>
8
9#include <botan/internal/fmt.h>
10#include <botan/internal/loadstor.h>
11#include <botan/internal/parsing.h>
12#include <bit>
13
14namespace Botan {
15
16namespace {
17
18/*
19* Convert a decimal-dotted string to binary IP
20*/
21std::optional<uint32_t> string_to_ipv4(std::string_view str) {
22 // At least 3 dots + 4 1-digit integers
23 // At most 3 dots + 4 3-digit integers
24 if(str.size() < 3 + 4 * 1 || str.size() > 3 + 4 * 3) {
25 return {};
26 }
27
28 // the final result
29 uint32_t ip = 0;
30 // the number of '.' seen so far
31 size_t dots = 0;
32 // accumulates one quad (range 0-255)
33 uint32_t accum = 0;
34 // # of digits pushed to accum since last dot
35 size_t cur_digits = 0;
36
37 for(const char c : str) {
38 if(c == '.') {
39 // . without preceding digit is invalid
40 if(cur_digits == 0) {
41 return {};
42 }
43 dots += 1;
44 // too many dots
45 if(dots > 3) {
46 return {};
47 }
48
49 cur_digits = 0;
50 ip = (ip << 8) | accum;
51 accum = 0;
52 } else if(c >= '0' && c <= '9') {
53 const auto d = static_cast<uint8_t>(c - '0');
54
55 // prohibit leading zero in quad (used for octal)
56 if(cur_digits > 0 && accum == 0) {
57 return {};
58 }
59 accum = (accum * 10) + d;
60
61 if(accum > 255) {
62 return {};
63 }
64
65 cur_digits++;
66 BOTAN_ASSERT_NOMSG(cur_digits <= 3);
67 } else {
68 return {};
69 }
70 }
71
72 // no trailing digits?
73 if(cur_digits == 0) {
74 return {};
75 }
76
77 // insufficient # of dots
78 if(dots != 3) {
79 return {};
80 }
81
82 ip = (ip << 8) | accum;
83
84 return ip;
85}
86
87} // namespace
88
89IPv4Address::IPv4Address(std::span<const uint8_t, 4> ip) : m_ip(load_be<uint32_t>(ip)) {}
90
91//static
92std::optional<IPv4Address> IPv4Address::from_string(std::string_view str) {
93 if(auto ipv4 = string_to_ipv4(str)) {
94 return IPv4Address(*ipv4);
95 } else {
96 return {};
97 }
98}
99
100//static
102 BOTAN_ARG_CHECK(bits <= 32, "IPv4 netmask prefix length must be at most 32");
103 if(bits == 0) {
104 return IPv4Address(0);
105 }
106 return IPv4Address(0xFFFFFFFF << (32 - bits));
107}
108
109std::array<uint8_t, 4> IPv4Address::to_bytes() const {
110 std::array<uint8_t, 4> out{};
111 store_be(m_ip, out);
112 return out;
113}
114
115std::string IPv4Address::to_string() const {
116 const auto addr = this->to_bytes();
117
118 std::string str;
119 str.reserve(15); // maximum possible size
120
121 for(size_t i = 0; i != 4; ++i) {
122 if(i > 0) {
123 str += '.';
124 }
125 str += std::to_string(addr[i]);
126 }
127
128 return str;
129}
130
131std::optional<size_t> IPv4Address::prefix_length() const {
132 // A 32-bit mask m is a CIDR prefix iff (~m) + 1 is a power of two or zero,
133 // i.e. (~m) & (~m + 1) == 0. If so, the prefix length is the leading-one count.
134 const uint32_t inv = ~m_ip;
135 if((inv & (inv + 1)) != 0) {
136 return std::nullopt;
137 }
138 return std::countl_one(m_ip);
139}
140
142 m_address(address & IPv4Address::netmask(prefix_length)), m_prefix_length(static_cast<uint8_t>(prefix_length)) {
143 // IPv4Address::netmask validates prefix_length <= 32, so by this point
144 // the static_cast is in range.
145}
146
147//static
148std::optional<IPv4Subnet> IPv4Subnet::from_address_and_mask(uint32_t addr, uint32_t mask) {
149 std::array<uint8_t, 8> addr_and_mask{};
150 store_be(&addr_and_mask[0], addr); // NOLINT(*-container-data-pointer)
151 store_be(&addr_and_mask[4], mask);
152 return IPv4Subnet::from_address_and_mask(addr_and_mask);
153}
154
155//static
156std::optional<IPv4Subnet> IPv4Subnet::from_address_and_mask(std::span<const uint8_t, 8> addr_and_mask) {
157 const IPv4Address addr(load_be<uint32_t>(addr_and_mask.data(), 0));
158 const IPv4Address mask(load_be<uint32_t>(addr_and_mask.data(), 1));
159
160 if(const auto plen = mask.prefix_length()) {
161 return IPv4Subnet(addr, *plen);
162 } else {
163 return {};
164 }
165}
166
167//static
168std::optional<IPv4Subnet> IPv4Subnet::from_string(std::string_view str) {
169 const auto slash = str.find('/');
170 if(slash == std::string_view::npos) {
171 return std::nullopt;
172 }
173
174 auto addr = IPv4Address::from_string(str.substr(0, slash));
175 if(!addr.has_value()) {
176 return std::nullopt;
177 }
178
179 // Parse the prefix length as a canonical decimal integer in [0, 32]
180 const auto plen_str = str.substr(slash + 1);
181
182 const auto plen = parse_sz(plen_str, /*require_canonical=*/true);
183
184 if(!plen.has_value() || plen.value() > 32) {
185 return std::nullopt;
186 }
187
188 const IPv4Subnet subnet(*addr, plen.value());
189
190 // Require the input to already be canonical: from_string and to_string
191 // are exact inverses, so a set host bit is rejected rather than masked away
192 if(subnet.to_string() != str) {
193 return std::nullopt;
194 }
195
196 return subnet;
197}
198
199bool IPv4Subnet::contains(const IPv4Address& ip) const {
200 return (ip & IPv4Address::netmask(m_prefix_length)) == m_address;
201}
202
204 return IPv4Address(m_address.address() | ~IPv4Address::netmask(m_prefix_length).address());
205}
206
207std::string IPv4Subnet::to_string() const {
208 return fmt("{}/{}", m_address.to_string(), static_cast<size_t>(m_prefix_length));
209}
210
211std::vector<uint8_t> IPv4Subnet::serialize() const {
212 std::vector<uint8_t> out;
213 if(is_host()) {
214 out.resize(4);
215 store_be(m_address.address(), out.data());
216 return out;
217 }
218 out.resize(8);
219 store_be(m_address.address(), out.data());
220 store_be(IPv4Address::netmask(m_prefix_length).address(), out.data() + 4);
221 return out;
222}
223
224} // namespace Botan
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
static std::optional< IPv4Address > from_string(std::string_view str)
std::optional< size_t > prefix_length() const
IPv4Address(uint32_t ip)
std::string to_string() const
Dotted-decimal form, e.g. "10.0.0.1".
std::array< uint8_t, 4 > to_bytes() const
The address as four bytes, network-byte-order.
static IPv4Address netmask(size_t bits)
static std::optional< IPv4Subnet > from_address_and_mask(std::span< const uint8_t, 8 > addr_and_mask)
std::vector< uint8_t > serialize() const
bool contains(const IPv4Address &ip) const
True iff ip falls within this subnet.
bool is_host() const
True iff prefix_length() == 32.
IPv4Subnet(IPv4Address address, size_t prefix_length)
size_t prefix_length() const
Prefix length in [0, 32].
static std::optional< IPv4Subnet > from_string(std::string_view str)
std::string to_string() const
CIDR-style "10.0.0.0/8".
IPv4Address last_address() const
The last address in this subnet (all host bits set).
const IPv4Address & address() const
The network address (host bits already zeroed).
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
std::optional< size_t > parse_sz(std::string_view input, bool require_canonical)
Definition parsing.cpp:71
constexpr auto store_be(ParamTs &&... params)
Definition loadstor.h:745
constexpr auto load_be(ParamTs &&... params)
Definition loadstor.h:504