util: Add a function for converting IP bytes to strings
We need this for future work which turns netlink data into IP addresses.
Tested:
Run through unit tests.
Change-Id: If078b28246509ca2ebd3bf7bab652b84258df0bd
Signed-off-by: William A. Kennington III <wak@google.com>
diff --git a/test/test_util.cpp b/test/test_util.cpp
index f536bd7..25953a1 100644
--- a/test/test_util.cpp
+++ b/test/test_util.cpp
@@ -1,5 +1,6 @@
#include "util.hpp"
+#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstddef>
@@ -44,6 +45,35 @@
EXPECT_EQ("70:FF:84:09:35:09", mac_address::toString(mac2));
}
+TEST_F(TestUtil, IpToString)
+{
+ struct in_addr ip1;
+ EXPECT_EQ(1, inet_pton(AF_INET, "192.168.10.1", &ip1));
+ EXPECT_EQ("192.168.10.1", toString(InAddrAny(ip1)));
+
+ struct in6_addr ip2;
+ EXPECT_EQ(1, inet_pton(AF_INET6, "fdd8:b5ad:9d93:94ee::2:1", &ip2));
+ EXPECT_EQ("fdd8:b5ad:9d93:94ee::2:1", toString(InAddrAny(ip2)));
+
+ InAddrAny ip3;
+ try
+ {
+ struct E
+ {
+ operator struct in6_addr()
+ {
+ throw 1;
+ }
+ };
+ ip3.emplace<struct in6_addr>(E());
+ EXPECT_TRUE(false);
+ }
+ catch (...)
+ {
+ }
+ EXPECT_THROW(toString(ip3), std::runtime_error);
+}
+
TEST_F(TestUtil, IpValidation)
{
std::string ipaddress = "0.0.0.0";