/* */ #include "DHTConnectionImpl.h" #include #include #include "LogFactory.h" #include "Logger.h" #include "RecoverableException.h" #include "util.h" #include "Socket.h" #include "SimpleRandomizer.h" namespace aria2 { DHTConnectionImpl::DHTConnectionImpl():socket_(new SocketCore(SOCK_DGRAM)), logger_(LogFactory::getInstance()) {} DHTConnectionImpl::~DHTConnectionImpl() {} bool DHTConnectionImpl::bind(uint16_t& port, IntSequence& ports) { std::vector randPorts = ports.flush(); std::random_shuffle(randPorts.begin(), randPorts.end(), *SimpleRandomizer::getInstance().get()); for(std::vector::const_iterator portItr = randPorts.begin(), eoi = randPorts.end(); portItr != eoi; ++portItr) { if(!(0 < (*portItr) && (*portItr) <= 65535)) { continue; } port = (*portItr); if(bind(port)) { return true; } } return false; } bool DHTConnectionImpl::bind(uint16_t& port) { try { socket_->bind(port); socket_->setNonBlockingMode(); std::pair svaddr; socket_->getAddrInfo(svaddr); port = svaddr.second; logger_->notice("DHT: listening to port %d", port); return true; } catch(RecoverableException& e) { logger_->error("Failed to bind for DHT. port=%u", e, port); } return false; } ssize_t DHTConnectionImpl::receiveMessage(unsigned char* data, size_t len, std::string& host, uint16_t& port) { std::pair remoteHost; ssize_t length = socket_->readDataFrom(data, len, remoteHost); if(length == 0) { return length; } else { host = remoteHost.first; port = remoteHost.second; return length; } } ssize_t DHTConnectionImpl::sendMessage(const unsigned char* data, size_t len, const std::string& host, uint16_t port) { return socket_->writeData(data, len, host, port); } } // namespace aria2