Commit b41eb6f0 authored by Angelo Failla's avatar Angelo Failla Committed by Facebook Github Bot

IPAddressV(46) methods to convert IPs to their inverse in-addr.arpa / ip6.arpa representation

Summary: As per the title, this adds methods to convert IPv(46) to their inverse representation, this is useful for applications that needs to calculate the inverse arpa representation, typically used when making PTR DNS requests.

Reviewed By: Orvid

Differential Revision: D4867502

fbshipit-source-id: 190e5c309b17a633e1c97b077f212ab38725860f
parent 19e3e9fe
......@@ -224,6 +224,16 @@ string IPAddressV4::str() const {
return detail::fastIpv4ToString(addr_.inAddr_);
}
// public
string IPAddressV4::toInverseArpaName() const {
return sformat(
"{}.{}.{}.{}.in-addr.arpa",
addr_.bytes_[3],
addr_.bytes_[2],
addr_.bytes_[1],
addr_.bytes_[0]);
}
// public
uint8_t IPAddressV4::getNthMSByte(size_t byteIndex) const {
const auto highestIndex = byteCount() - 1;
......
......@@ -183,6 +183,8 @@ class IPAddressV4 {
// @see IPAddress#str
std::string str() const;
std::string toInverseArpaName() const;
// return underlying in_addr structure
in_addr toAddr() const { return addr_.inAddr_; }
......
......@@ -397,6 +397,19 @@ string IPAddressV6::toFullyQualified() const {
return detail::fastIpv6ToString(addr_.in6Addr_);
}
// public
string IPAddressV6::toInverseArpaName() const {
constexpr folly::StringPiece lut = "0123456789abcdef";
std::array<char, 32> a;
int j = 0;
for (int i = 15; i >= 0; i--) {
a[j] = (lut[bytes()[i] & 0xf]);
a[j + 1] = (lut[bytes()[i] >> 4]);
j += 2;
}
return sformat("{}.ip6.arpa", join(".", a));
}
// public
uint8_t IPAddressV6::getNthMSByte(size_t byteIndex) const {
const auto highestIndex = byteCount() - 1;
......
......@@ -274,6 +274,8 @@ class IPAddressV6 {
// @see IPAddress#toFullyQualified
std::string toFullyQualified() const;
std::string toInverseArpaName() const;
// @see IPAddress#str
std::string str() const;
......
......@@ -405,6 +405,17 @@ TEST(IPAddress, ToString) {
" - ", addr_1, " - ", addr_10_1_2_3));
}
TEST(IPaddress, toInverseArpaName) {
IPAddressV4 addr_ipv4("10.0.0.1");
EXPECT_EQ("1.0.0.10.in-addr.arpa", addr_ipv4.toInverseArpaName());
IPAddressV6 addr_ipv6("2620:0000:1cfe:face:b00c:0000:0000:0003");
EXPECT_EQ(
sformat(
"{}.ip6.arpa",
"3.0.0.0.0.0.0.0.0.0.0.0.c.0.0.b.e.c.a.f.e.f.c.1.0.0.0.0.0.2.6.2"),
addr_ipv6.toInverseArpaName());
}
// Test that invalid string values are killed
TEST_P(IPAddressCtorTest, InvalidCreation) {
string addr = GetParam();
......
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