Commit fa9cc998 authored by Florent Thoumie's avatar Florent Thoumie Committed by facebook-github-bot-1

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
parent e56b41ec
...@@ -68,6 +68,13 @@ class IPAddressV4 : boost::totally_ordered<IPAddressV4> { ...@@ -68,6 +68,13 @@ class IPAddressV4 : boost::totally_ordered<IPAddressV4> {
return addr; 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. * Convert a IPv4 address string to a long in network byte order.
* @param [in] ip the address to convert * @param [in] ip the address to convert
......
...@@ -96,6 +96,13 @@ class IPAddressV6 : boost::totally_ordered<IPAddressV6> { ...@@ -96,6 +96,13 @@ class IPAddressV6 : boost::totally_ordered<IPAddressV6> {
return addr; 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. * Default constructor for IPAddressV6.
* *
......
...@@ -631,6 +631,22 @@ TEST(IPAddress, fromBinaryV4) { ...@@ -631,6 +631,22 @@ TEST(IPAddress, fromBinaryV4) {
IPAddressFormatException); 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<pair<string, vector<uint8_t> > > provideBinary16Bytes = { static const vector<pair<string, vector<uint8_t> > > provideBinary16Bytes = {
{"::0", {"::0",
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
...@@ -677,6 +693,17 @@ TEST(IPAddress, fromBinaryV6) { ...@@ -677,6 +693,17 @@ TEST(IPAddress, fromBinaryV6) {
IPAddressFormatException); 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) { TEST_P(IPAddressFlagTest, IsLoopback) {
AddressFlags param = GetParam(); AddressFlags param = GetParam();
IPAddress addr(param.address); IPAddress addr(param.address);
......
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