From fa9cc998742a2d675fbf18e1532a6568263146a7 Mon Sep 17 00:00:00 2001 From: Florent Thoumie Date: Mon, 26 Oct 2015 14:53:03 -0700 Subject: [PATCH] Add new toBinary() function to IPAddress. Summary: This is pretty much the reverse operation from the fromBinary() constructor. Reviewed By: yfeldblum Differential Revision: D2578680 fb-gh-sync-id: d8c4e53fe8bc0f5373ebb0b4f7ee498659c1b003 --- folly/IPAddressV4.h | 7 +++++++ folly/IPAddressV6.h | 7 +++++++ folly/test/IPAddressTest.cpp | 27 +++++++++++++++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/folly/IPAddressV4.h b/folly/IPAddressV4.h index bc7be1cf..1feac577 100644 --- a/folly/IPAddressV4.h +++ b/folly/IPAddressV4.h @@ -68,6 +68,13 @@ class IPAddressV4 : boost::totally_ordered { return addr; } + /** + * Returns the address as a Range. + */ + ByteRange toBinary() const { + return ByteRange((const unsigned char *) &addr_.inAddr_.s_addr, 4); + } + /** * Convert a IPv4 address string to a long in network byte order. * @param [in] ip the address to convert diff --git a/folly/IPAddressV6.h b/folly/IPAddressV6.h index d4876af6..22ff3651 100644 --- a/folly/IPAddressV6.h +++ b/folly/IPAddressV6.h @@ -96,6 +96,13 @@ class IPAddressV6 : boost::totally_ordered { return addr; } + /** + * Returns the address as a Range. + */ + ByteRange toBinary() const { + return ByteRange((const unsigned char *) &addr_.in6Addr_.s6_addr, 16); + } + /** * Default constructor for IPAddressV6. * diff --git a/folly/test/IPAddressTest.cpp b/folly/test/IPAddressTest.cpp index f603fe12..679c7623 100644 --- a/folly/test/IPAddressTest.cpp +++ b/folly/test/IPAddressTest.cpp @@ -631,6 +631,22 @@ TEST(IPAddress, fromBinaryV4) { IPAddressFormatException); } +TEST(IPAddress, toBinaryV4) { + for (auto& tc : provideToLong) { + SCOPED_TRACE(tc.first); + union { + uint8_t u8[4]; + uint32_t u32; + } data; + data.u32 = Endian::big(tc.second); + ByteRange bytes(data.u8, 4); + + auto fromBin = IPAddressV4::fromBinary(bytes); + auto toBin = fromBin.toBinary(); + EXPECT_EQ(bytes, toBin); + } +} + static const vector > > provideBinary16Bytes = { {"::0", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -677,6 +693,17 @@ TEST(IPAddress, fromBinaryV6) { IPAddressFormatException); } +TEST(IPAddress, toBinaryV6) { + for (auto& tc : provideBinary16Bytes) { + SCOPED_TRACE(tc.first); + ByteRange bytes(&tc.second.front(), tc.second.size()); + + auto fromBin = IPAddressV6::fromBinary(bytes); + auto toBin = fromBin.toBinary(); + EXPECT_EQ(bytes, toBin); + } +} + TEST_P(IPAddressFlagTest, IsLoopback) { AddressFlags param = GetParam(); IPAddress addr(param.address); -- 2.34.1