diff --git a/include/opendht/sockaddr.h b/include/opendht/sockaddr.h index 8f9463259d03c9530d6ab5eddbb53297e995e35c..37efa2d92c7d5e24a6a51469007cc42809f69994 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 87826e1fca2a0002726e2960bc77fed6f46db122..18e946a09c6e9db57b8a9ebef8a29ba7a19eeb80 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) {