Expose isFamilyInet() to check if SocketAddress is a valid ipv4 or ipv6
authorAli Zaveri <azaveri@fb.com>
Wed, 9 Nov 2016 08:29:32 +0000 (00:29 -0800)
committerFacebook Github Bot <facebook-github-bot-bot@fb.com>
Wed, 9 Nov 2016 08:38:27 +0000 (00:38 -0800)
Summary: Expose isFamilyInet() in SocketAddress. This cleans up code and provides a way to validate if SocketAddress is a ipv4 or ipv6

Differential Revision: D4150650

fbshipit-source-id: dc8883e904b6577fc27bdd54064fcc50de93b0d2

folly/SocketAddress.cpp
folly/SocketAddress.h
folly/test/SocketAddressTest.cpp

index cd1ebdf8c69bfb4b9d406e6063f230d78610cd86..1107e0e0f54f628349d50833cc6bd756d902b315 100644 (file)
@@ -365,21 +365,24 @@ socklen_t SocketAddress::getActualSize() const {
 }
 
 std::string SocketAddress::getFullyQualified() const {
-  auto family = getFamily();
-  if (family != AF_INET && family != AF_INET6) {
+  if (!isFamilyInet()) {
     throw std::invalid_argument("Can't get address str for non ip address");
   }
   return storage_.addr.toFullyQualified();
 }
 
 std::string SocketAddress::getAddressStr() const {
-  auto family = getFamily();
-  if (family != AF_INET && family != AF_INET6) {
+  if (!isFamilyInet()) {
     throw std::invalid_argument("Can't get address str for non ip address");
   }
   return storage_.addr.str();
 }
 
+bool SocketAddress::isFamilyInet() const {
+  auto family = getFamily();
+  return family == AF_INET || family == AF_INET6;
+}
+
 void SocketAddress::getAddressStr(char* buf, size_t buflen) const {
   auto ret = getAddressStr();
   size_t len = std::min(buflen - 1, ret.size());
index e4edfbb68d6826712d4b2ac3c0ab800ac318ee42..388a720ee8938bf32e6cbc3877cd226248366824 100644 (file)
@@ -415,6 +415,11 @@ class SocketAddress {
    */
   void getAddressStr(char* buf, size_t buflen) const;
 
+  /**
+   * Return true if it is a valid IPv4 or IPv6 address.
+   */
+  bool isFamilyInet() const;
+
   /**
    * For v4 & v6 addresses, return the fully qualified address string
    */
index 6a95db98f1040a60461621c34738c43080d92b15..66bfd4525f556a7ff751b1626cf468d81a18a63c 100644 (file)
@@ -909,3 +909,15 @@ TEST(SocketAddress, ResetIPAddress) {
   EXPECT_FALSE(addr.isInitialized());
   EXPECT_TRUE(addr.empty());
 }
+
+TEST(SocketAddress, ValidFamilyInet) {
+  SocketAddress addr;
+  EXPECT_FALSE(addr.isFamilyInet());
+  folly::IPAddress ipAddr("123.234.0.23");
+  addr.setFromIpAddrPort(ipAddr, 8888);
+  EXPECT_TRUE(addr.isFamilyInet());
+
+  folly::IPAddress ip6Addr("2620:0:1cfe:face:b00c::3");
+  SocketAddress addr6(ip6Addr, 8888);
+  EXPECT_TRUE(addr6.isFamilyInet());
+}