From 01dbb37f94558e8793137943b5fd97fe9d64d594 Mon Sep 17 00:00:00 2001 From: Yedidya Feldblum Date: Mon, 16 May 2016 18:43:22 -0700 Subject: [PATCH] IPAddress::validate Summary: [Folly] `IPAddress::validate`. Reviewed By: igorsugak Differential Revision: D3308683 fbshipit-source-id: 48af18d6930f16718372021a4cc08062bf17327e --- folly/IPAddress.cpp | 4 ++++ folly/IPAddress.h | 3 +++ folly/IPAddressV4.h | 1 + folly/IPAddressV6.h | 1 + folly/test/IPAddressTest.cpp | 6 ++++++ 5 files changed, 15 insertions(+) diff --git a/folly/IPAddress.cpp b/folly/IPAddress.cpp index 93fbab81..9fa6c59d 100644 --- a/folly/IPAddress.cpp +++ b/folly/IPAddress.cpp @@ -44,6 +44,10 @@ void toAppend(IPAddress addr, fbstring* result) { result->append(addr.str()); } +bool IPAddress::validate(StringPiece ip) { + return IPAddressV4::validate(ip) || IPAddressV6::validate(ip); +} + // public static IPAddressV4 IPAddress::createIPv4(const IPAddress& addr) { if (addr.isV4()) { diff --git a/folly/IPAddress.h b/folly/IPAddress.h index ce51cb7e..52b00a8a 100644 --- a/folly/IPAddress.h +++ b/folly/IPAddress.h @@ -70,6 +70,9 @@ typedef std::pair CIDRNetwork; */ class IPAddress : boost::totally_ordered { public: + // returns true iff the input string can be parsed as an ip-address + static bool validate(StringPiece ip); + // return the V4 representation of the address, converting it from V6 to V4 if // needed. Note that this will throw an IPAddressFormatException if the V6 // address is not IPv4Mapped. diff --git a/folly/IPAddressV4.h b/folly/IPAddressV4.h index 02c93114..fa4d46d2 100644 --- a/folly/IPAddressV4.h +++ b/folly/IPAddressV4.h @@ -53,6 +53,7 @@ typedef std::array ByteArray4; */ class IPAddressV4 : boost::totally_ordered { public: + // returns true iff the input string can be parsed as an ipv4-address static bool validate(StringPiece ip); // create an IPAddressV4 instance from a uint32_t (network byte order) diff --git a/folly/IPAddressV6.h b/folly/IPAddressV6.h index be32b4aa..703f9da7 100644 --- a/folly/IPAddressV6.h +++ b/folly/IPAddressV6.h @@ -86,6 +86,7 @@ class IPAddressV6 : boost::totally_ordered { static constexpr size_t kToFullyQualifiedSize = 8 /*words*/ * 4 /*hex chars per word*/ + 7 /*separators*/; + // returns true iff the input string can be parsed as an ipv6-address static bool validate(StringPiece ip); /** diff --git a/folly/test/IPAddressTest.cpp b/folly/test/IPAddressTest.cpp index c9c6a8ad..566a73cf 100644 --- a/folly/test/IPAddressTest.cpp +++ b/folly/test/IPAddressTest.cpp @@ -235,6 +235,12 @@ TEST(IPAddressV6, validate) { IPAddressV6::validate("2620:0000:1cfe:face:b00c:0000:127.127.127.127")); } +TEST(IPAddress, validate) { + EXPECT_TRUE(IPAddress::validate("0.0.0.0")); + EXPECT_TRUE(IPAddress::validate("::")); + EXPECT_FALSE(IPAddress::validate("asdf")); +} + // Test addresses constructed using a in[6]_addr value TEST_P(IPAddressTest, CtorAddress) { AddressData param = GetParam(); -- 2.34.1