IPAddress::validate
authorYedidya Feldblum <yfeldblum@fb.com>
Tue, 17 May 2016 01:43:22 +0000 (18:43 -0700)
committerFacebook Github Bot 1 <facebook-github-bot-1-bot@fb.com>
Tue, 17 May 2016 01:53:26 +0000 (18:53 -0700)
Summary: [Folly] `IPAddress::validate`.

Reviewed By: igorsugak

Differential Revision: D3308683

fbshipit-source-id: 48af18d6930f16718372021a4cc08062bf17327e

folly/IPAddress.cpp
folly/IPAddress.h
folly/IPAddressV4.h
folly/IPAddressV6.h
folly/test/IPAddressTest.cpp

index 93fbab8126df5e51c99255853579e355c8c6b234..9fa6c59d63a52de8abab265ba140b0436d56fea5 100644 (file)
@@ -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()) {
index ce51cb7ea373aaf22776aca78ccea94fabf7fe49..52b00a8a7b4952132391d86f7ec4076787434a26 100644 (file)
@@ -70,6 +70,9 @@ typedef std::pair<IPAddress, uint8_t> CIDRNetwork;
  */
 class IPAddress : boost::totally_ordered<IPAddress> {
  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.
index 02c93114f25703940cead58730d5ef6accd4578b..fa4d46d277702133484cbe3baf8e420dd68c7c1a 100644 (file)
@@ -53,6 +53,7 @@ typedef std::array<uint8_t, 4> ByteArray4;
  */
 class IPAddressV4 : boost::totally_ordered<IPAddressV4> {
  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)
index be32b4aaaedcb67137593ad45dac018a4c0b719c..703f9da71e5ffeca96047bf5a8ab80bcc1fab66f 100644 (file)
@@ -86,6 +86,7 @@ class IPAddressV6 : boost::totally_ordered<IPAddressV6> {
   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);
 
   /**
index c9c6a8ad46ad32b56c6e0cc73149c22ef089fafc..566a73cf7edea5d1f841dee638b2cc77172570c5 100644 (file)
@@ -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();