28 #include <boost/utility/value_init.hpp>
37 const boost::asio::ip::address& maxAddress)
38 : m_minAddress(minAddress)
39 , m_maxAddress(maxAddress)
46 using boost::asio::ip::address_v4;
47 static Network range{address_v4{}, address_v4{0xffffffff}};
54 using boost::asio::ip::address_v6;
55 static address_v6::bytes_type maxV6 = {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
56 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}};
57 static Network range{address_v6{}, address_v6{maxV6}};
64 auto pos = cidr.find(
'/');
65 if (pos == std::string::npos) {
70 boost::lexical_cast<Network>(cidr);
73 catch (
const boost::bad_lexical_cast&) {
81 return os << network.m_minAddress <<
" <-> " << network.m_maxAddress;
87 namespace ip = boost::asio::ip;
89 std::string networkStr;
92 size_t position = networkStr.find(
'/');
93 if (position == std::string::npos) {
95 network.m_minAddress = ip::address::from_string(networkStr);
96 network.m_maxAddress = ip::address::from_string(networkStr);
98 catch (
const boost::system::system_error&) {
99 is.setstate(std::ios::failbit);
104 boost::system::error_code ec;
105 auto address = ip::address::from_string(networkStr.substr(0, position), ec);
107 is.setstate(std::ios::failbit);
111 auto prefixLenStr = networkStr.substr(position + 1);
112 if (!std::all_of(prefixLenStr.begin(), prefixLenStr.end(),
113 [] (
unsigned char c) { return std::isdigit(c); })) {
114 is.setstate(std::ios::failbit);
119 mask = boost::lexical_cast<size_t>(prefixLenStr);
121 catch (
const boost::bad_lexical_cast&) {
122 is.setstate(std::ios::failbit);
126 if (address.is_v4()) {
128 is.setstate(std::ios::failbit);
132 ip::address_v4::bytes_type maskBytes = boost::initialized_value;
133 for (
size_t i = 0; i < mask; i++) {
134 size_t byteId = i / 8;
135 size_t bitIndex = 7 - i % 8;
136 maskBytes[byteId] |= (1 << bitIndex);
139 ip::address_v4::bytes_type addressBytes = address.to_v4().to_bytes();
140 ip::address_v4::bytes_type min;
141 ip::address_v4::bytes_type max;
143 for (
size_t i = 0; i < addressBytes.size(); i++) {
144 min[i] = addressBytes[i] & maskBytes[i];
145 max[i] = addressBytes[i] | ~(maskBytes[i]);
148 network.m_minAddress = ip::address_v4(min);
149 network.m_maxAddress = ip::address_v4(max);
153 is.setstate(std::ios::failbit);
157 ip::address_v6::bytes_type maskBytes = boost::initialized_value;
158 for (
size_t i = 0; i < mask; i++) {
159 size_t byteId = i / 8;
160 size_t bitIndex = 7 - i % 8;
161 maskBytes[byteId] |= (1 << bitIndex);
164 ip::address_v6::bytes_type addressBytes = address.to_v6().to_bytes();
165 ip::address_v6::bytes_type min;
166 ip::address_v6::bytes_type max;
168 for (
size_t i = 0; i < addressBytes.size(); i++) {
169 min[i] = addressBytes[i] & maskBytes[i];
170 max[i] = addressBytes[i] | ~(maskBytes[i]);
173 network.m_minAddress = ip::address_v6(min);
174 network.m_maxAddress = ip::address_v6(max);