From 9948079c9749c32f9e1c5a43ab68c9172baa065c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Adrien=20B=C3=A9raud?= <adrien.beraud@savoirfairelinux.com>
Date: Fri, 10 Nov 2017 17:47:09 -0500
Subject: [PATCH] SockAddr: add resolve()

---
 include/opendht/sockaddr.h |  3 +++
 src/utils.cpp              | 25 +++++++++++++++++++++++++
 2 files changed, 28 insertions(+)

diff --git a/include/opendht/sockaddr.h b/include/opendht/sockaddr.h
index 8f946325..37efa2d9 100644
--- a/include/opendht/sockaddr.h
+++ b/include/opendht/sockaddr.h
@@ -36,6 +36,7 @@ typedef uint16_t in_port_t;
 
 #include <string>
 #include <memory>
+#include <vector>
 
 #include <cstring>
 #include <cstddef>
@@ -71,6 +72,8 @@ public:
      */
     SockAddr(const sockaddr_storage& ss, socklen_t len) : SockAddr((const sockaddr*)&ss, len) {}
 
+    static std::vector<SockAddr> resolve(const std::string& host, const std::string& service = {});
+
     bool operator<(const SockAddr& o) const {
         if (len != o.len)
             return len < o.len;
diff --git a/src/utils.cpp b/src/utils.cpp
index 87826e1f..18e946a0 100644
--- a/src/utils.cpp
+++ b/src/utils.cpp
@@ -27,6 +27,31 @@
 
 namespace dht {
 
+std::vector<SockAddr>
+SockAddr::resolve(const std::string& host, const std::string& service)
+{
+    std::vector<SockAddr> ips {};
+    if (host.empty())
+        return ips;
+
+    addrinfo hints;
+    memset(&hints, 0, sizeof(hints));
+    hints.ai_socktype = SOCK_DGRAM;
+    addrinfo* info = nullptr;
+    int rc = getaddrinfo(host.c_str(), service.c_str(), &hints, &info);
+    if(rc != 0)
+        throw std::invalid_argument(std::string("Error: `") + host + ":" + service + "`: " + gai_strerror(rc));
+
+    addrinfo* infop = info;
+    while (infop) {
+        ips.emplace_back(infop->ai_addr, infop->ai_addrlen);
+        infop = infop->ai_next;
+    }
+    freeaddrinfo(info);
+    return ips;
+}
+
+
 std::string
 print_addr(const sockaddr* sa, socklen_t slen)
 {
-- 
GitLab