Commit 351ce9ee authored by Tomek Mrugalski's avatar Tomek Mrugalski 🛰
Browse files

[1226] from_uint32 and operator uint32_t implemented in IOAddress

parent ba1568e6
......@@ -15,6 +15,7 @@
#include <config.h>
#include <unistd.h> // for some IPC/network system calls
#include <stdint.h>
#include <sys/socket.h>
#include <netinet/in.h>
......@@ -70,6 +71,11 @@ IOAddress::from_bytes(short family, const uint8_t* data) {
return IOAddress(string(addr_str));
}
IOAddress
IOAddress::from_uint32(uint32_t v4address) {
return IOAddress(asio::ip::address_v4(v4address));
}
short
IOAddress::getFamily() const {
if (asio_address_.is_v4()) {
......@@ -84,5 +90,14 @@ IOAddress::getAddress() const {
return asio_address_;
}
IOAddress::operator uint32_t() const {
if (getAddress().is_v4()) {
return (getAddress().to_v4().to_ulong());
} else {
isc_throw(BadValue, "Can't convert " << toText()
<< " address to IPv4.");
}
}
} // namespace asiolink
} // namespace isc
......@@ -19,6 +19,7 @@
// this file. In particular, asio.hpp should never be included here.
// See the description of the namespace below.
#include <unistd.h> // for some network system calls
#include <stdint.h> // for uint32_t
#include <asio/ip/address.hpp>
#include <functional>
......@@ -103,6 +104,15 @@ public:
static IOAddress
from_bytes(short family, const uint8_t* data);
/// \brief Creates an IPv4 address from uint32 value
///
/// \param v4address specified IPv4 address in network
/// byte order
///
/// \return Created IOAddress that holds IPv4 address
static IOAddress
from_uint32(uint32_t v4address);
/// \brief Compare addresses for equality
///
/// \param other Address to compare against.
......@@ -139,6 +149,14 @@ public:
return (nequals(other));
}
/// \brief Converts IPv4 address to uint32_t
///
/// Will throw BadValue exception if that is not IPv4
/// address.
///
/// \return uint32_t that represents IPv4 address in
/// network byte order
operator uint32_t () const;
private:
asio::ip::address asio_address_;
......
......@@ -83,3 +83,19 @@ TEST(IOAddressTest, from_bytes) {
});
EXPECT_EQ(addr.toText(), IOAddress("192.0.2.3").toText());
}
TEST(IOAddressTest, uint32) {
IOAddress addr1("192.0.2.5");
// operator uint_32() is used here
uint32_t tmp = addr1;
uint32_t expected = (192U << 24) + (0U << 16) + (2U << 8) + 5U;
EXPECT_EQ(expected, tmp);
// now let's try opposite conversion
IOAddress addr3 = IOAddress::from_uint32(expected);
EXPECT_EQ(addr3.toText(), "192.0.2.5");
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment