From: Ali Zaveri Date: Wed, 9 Nov 2016 08:29:32 +0000 (-0800) Subject: Expose isFamilyInet() to check if SocketAddress is a valid ipv4 or ipv6 X-Git-Tag: v2016.11.14.00~23 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=9bb2b0dfcb597b8cbdf0e6db4af2607d64740cb3;p=folly.git Expose isFamilyInet() to check if SocketAddress is a valid ipv4 or ipv6 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 --- diff --git a/folly/SocketAddress.cpp b/folly/SocketAddress.cpp index cd1ebdf8..1107e0e0 100644 --- a/folly/SocketAddress.cpp +++ b/folly/SocketAddress.cpp @@ -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()); diff --git a/folly/SocketAddress.h b/folly/SocketAddress.h index e4edfbb6..388a720e 100644 --- a/folly/SocketAddress.h +++ b/folly/SocketAddress.h @@ -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 */ diff --git a/folly/test/SocketAddressTest.cpp b/folly/test/SocketAddressTest.cpp index 6a95db98..66bfd452 100644 --- a/folly/test/SocketAddressTest.cpp +++ b/folly/test/SocketAddressTest.cpp @@ -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()); +}