danicoin/src/Platform/Linux/System/Ipv4Resolver.cpp

74 lines
2 KiB
C++
Raw Normal View History

// Copyright (c) 2011-2015 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
2015-05-27 12:08:46 +00:00
#include "Ipv4Resolver.h"
#include <cassert>
#include <random>
#include <stdexcept>
#include <netdb.h>
2015-07-30 15:22:07 +00:00
#include <System/Dispatcher.h>
2015-08-05 13:09:05 +00:00
#include <System/ErrorMessage.h>
2015-05-27 12:08:46 +00:00
#include <System/InterruptedException.h>
#include <System/Ipv4Address.h>
namespace System {
Ipv4Resolver::Ipv4Resolver() : dispatcher(nullptr) {
}
2015-07-30 15:22:07 +00:00
Ipv4Resolver::Ipv4Resolver(Dispatcher& dispatcher) : dispatcher(&dispatcher) {
2015-05-27 12:08:46 +00:00
}
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);
2015-07-30 15:22:07 +00:00
if (dispatcher->interrupted()) {
2015-05-27 12:08:46 +00:00
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) {
2015-08-05 13:09:05 +00:00
throw std::runtime_error("Ipv4Resolver::resolve, getaddrinfo failed, " + errorMessage(result));
2015-05-27 12:08:46 +00:00
}
std::size_t count = 0;
for (addrinfo* addressInfo = addressInfos; addressInfo != nullptr; addressInfo = addressInfo->ai_next) {
++count;
}
std::mt19937 generator{ std::random_device()() };
std::size_t index = std::uniform_int_distribution<std::size_t>(0, count - 1)(generator);
addrinfo* addressInfo = addressInfos;
for (std::size_t i = 0; i < index; ++i) {
addressInfo = addressInfo->ai_next;
}
Ipv4Address address(ntohl(reinterpret_cast<sockaddr_in*>(addressInfo->ai_addr)->sin_addr.s_addr));
freeaddrinfo(addressInfo);
return address;
}
}