Electroneum
Loading...
Searching...
No Matches
net_helper.cpp
Go to the documentation of this file.
1#include "net/net_helper.h"
2
3namespace epee
4{
5namespace net_utils
6{
7 boost::unique_future<boost::asio::ip::tcp::socket>
8 direct_connect::operator()(const std::string& addr, const std::string& port, boost::asio::steady_timer& timeout) const
9 {
10 // Get a list of endpoints corresponding to the server name.
12 boost::asio::ip::tcp::resolver resolver(GET_IO_SERVICE(timeout));
13 boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), addr, port, boost::asio::ip::tcp::resolver::query::canonical_name);
14 boost::asio::ip::tcp::resolver::iterator iterator = resolver.resolve(query);
15 boost::asio::ip::tcp::resolver::iterator end;
16 if(iterator == end) // Documentation states that successful call is guaranteed to be non-empty
17 throw boost::system::system_error{boost::asio::error::fault, "Failed to resolve " + addr};
18
20
21 struct new_connection
22 {
23 boost::promise<boost::asio::ip::tcp::socket> result_;
24 boost::asio::ip::tcp::socket socket_;
25
26 explicit new_connection(boost::asio::io_service& io_service)
27 : result_(), socket_(io_service)
28 {}
29 };
30
31 const auto shared = std::make_shared<new_connection>(GET_IO_SERVICE(timeout));
32 timeout.async_wait([shared] (boost::system::error_code error)
33 {
34 if (error != boost::system::errc::operation_canceled && shared && shared->socket_.is_open())
35 {
36 shared->socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
37 shared->socket_.close();
38 }
39 });
40 shared->socket_.async_connect(*iterator, [shared] (boost::system::error_code error)
41 {
42 if (shared)
43 {
44 if (error)
45 shared->result_.set_exception(boost::system::system_error{error});
46 else
47 shared->result_.set_value(std::move(shared->socket_));
48 }
49 });
50 return shared->result_.get_future();
51 }
52}
53}
54
#define GET_IO_SERVICE(s)
boost::unique_future< boost::asio::ip::tcp::socket > operator()(const std::string &addr, const std::string &port, boost::asio::steady_timer &) const
Definition net_helper.cpp:8