Commit 9bb2b0df authored by Ali Zaveri's avatar Ali Zaveri Committed by Facebook Github Bot

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
parent 4aa69c20
......@@ -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());
......
......@@ -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
*/
......
......@@ -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());
}
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