// Copyright (c) 2011-2016 The Cryptonote developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "Ipv4Resolver.h" #include #include #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include #include #include #include #include namespace System { Ipv4Resolver::Ipv4Resolver() : dispatcher(nullptr) { } Ipv4Resolver::Ipv4Resolver(Dispatcher& dispatcher) : dispatcher(&dispatcher) { } Ipv4Resolver::Ipv4Resolver(Ipv4Resolver&& other) : dispatcher(other.dispatcher) { if (dispatcher != nullptr) { other.dispatcher = nullptr; } } Ipv4Resolver::~Ipv4Resolver() { } Ipv4Resolver& Ipv4Resolver::operator=(Ipv4Resolver&& other) { dispatcher = other.dispatcher; if (dispatcher != nullptr) { other.dispatcher = nullptr; } return *this; } Ipv4Address Ipv4Resolver::resolve(const std::string& host) { assert(dispatcher != nullptr); if (dispatcher->interrupted()) { throw InterruptedException(); } addrinfo hints = { 0, AF_INET, SOCK_STREAM, IPPROTO_TCP, 0, NULL, NULL, NULL }; addrinfo* addressInfos; int result = getaddrinfo(host.c_str(), NULL, &hints, &addressInfos); if (result != 0) { throw std::runtime_error("Ipv4Resolver::resolve, getaddrinfo failed, " + errorMessage(result)); } size_t count = 0; for (addrinfo* addressInfo = addressInfos; addressInfo != nullptr; addressInfo = addressInfo->ai_next) { ++count; } std::mt19937 generator{ std::random_device()() }; size_t index = std::uniform_int_distribution(0, count - 1)(generator); addrinfo* addressInfo = addressInfos; for (size_t i = 0; i < index; ++i) { addressInfo = addressInfo->ai_next; } Ipv4Address address(ntohl(reinterpret_cast(addressInfo->ai_addr)->sin_addr.S_un.S_addr)); freeaddrinfo(addressInfo); return address; } }