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/util.cpp b/util.cpp
index 7aa4e2a..db164e6 100644
--- a/util.cpp
+++ b/util.cpp
@@ -14,6 +14,7 @@
 #include <list>
 #include <phosphor-logging/elog-errors.hpp>
 #include <phosphor-logging/log.hpp>
+#include <stdexcept>
 #include <string>
 #include <xyz/openbmc_project/Common/error.hpp>
 
@@ -203,6 +204,35 @@
     return networkString;
 }
 
+std::string toString(const InAddrAny& addr)
+{
+    std::string ip;
+    if (std::holds_alternative<struct in_addr>(addr))
+    {
+        const auto& v = std::get<struct in_addr>(addr);
+        ip.resize(INET_ADDRSTRLEN);
+        if (inet_ntop(AF_INET, &v, ip.data(), ip.size()) == NULL)
+        {
+            throw std::runtime_error("Failed to convert IP4 to string");
+        }
+    }
+    else if (std::holds_alternative<struct in6_addr>(addr))
+    {
+        const auto& v = std::get<struct in6_addr>(addr);
+        ip.resize(INET6_ADDRSTRLEN);
+        if (inet_ntop(AF_INET6, &v, ip.data(), ip.size()) == NULL)
+        {
+            throw std::runtime_error("Failed to convert IP6 to string");
+        }
+    }
+    else
+    {
+        throw std::runtime_error("Invalid addr type");
+    }
+    ip.resize(strlen(ip.c_str()));
+    return ip;
+}
+
 bool isLinkLocalIP(const std::string& address)
 {
     return address.find(IPV4_PREFIX) == 0 || address.find(IPV6_PREFIX) == 0;