diff --git a/include/tins/ip_address.h b/include/tins/ip_address.h index 1fdf636..8b7eff4 100644 --- a/include/tins/ip_address.h +++ b/include/tins/ip_address.h @@ -53,6 +53,13 @@ public: */ static const IPv4Address broadcast; + /** + * \brief Constructs an IPv4 address from a prefix length + * + * \param prefix_length The length of the prefix + */ + static IPv4Address from_prefix_length(uint32_t prefix_length); + /** * \brief Constructor taking a const char*. * diff --git a/src/address_range.cpp b/src/address_range.cpp index 00291a9..89df754 100644 --- a/src/address_range.cpp +++ b/src/address_range.cpp @@ -39,15 +39,12 @@ IPv4Range operator/(const IPv4Address& addr, int mask) { if (mask > 32) { throw logic_error("Prefix length cannot exceed 32"); } - return IPv4Range::from_mask( - addr, - IPv4Address(Endian::host_to_be(0xffffffff << (32 - mask))) - ); + return IPv4Range::from_mask(addr, IPv4Address::from_prefix_length(mask)); } IPv6Range operator/(const IPv6Address& addr, int mask) { if (mask > 128) { - throw std::logic_error("Prefix length cannot exceed 128"); + throw logic_error("Prefix length cannot exceed 128"); } return IPv6Range::from_mask(addr, IPv6Address::from_prefix_length(mask)); } diff --git a/src/ip_address.cpp b/src/ip_address.cpp index 7b8e898..e0e97d3 100644 --- a/src/ip_address.cpp +++ b/src/ip_address.cpp @@ -54,7 +54,11 @@ const AddressRange private_ranges[] = { const AddressRange loopback_range = IPv4Address("127.0.0.0") / 8; const AddressRange multicast_range = IPv4Address("224.0.0.0") / 4; - + +IPv4Address IPv4Address::from_prefix_length(uint32_t prefix_length) { + return IPv4Address(Endian::host_to_be(0xffffffff << (32 - prefix_length))); +} + IPv4Address::IPv4Address(uint32_t ip) : ip_addr_(Endian::be_to_host(ip)) {