15

I'm starting with boost asio programming in C++ and when looking over the examples I just can't understand what does boost::asio::ip::tcp::resolver::iterator do.

Code:

boost::asio::io_service io_service;

tcp::resolver resolver(io_service);
tcp::resolver::query query(argv[1]);
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;

tcp::socket socket(io_service);
boost::system::error_code error = boost::asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
  socket.close();
  socket.connect(*endpoint_iterator++, error);
}

Please help me and excuse me if my question doesn't provide enough information.

Sam Miller
  • 23,808
  • 4
  • 67
  • 87
Hami
  • 704
  • 2
  • 9
  • 27

1 Answers1

22

boost::asio::ip::tcp::resolver::iterator iterates through the address list of the host that you specified (hosts can have multiple addresses).

Like an std::string::iterator iterates through its characters, boost::asio::ip::tcp::resolver::iterator iterates through its address list.

The following code:

while (error && endpoint_iterator != end)
{
  socket.close();
  socket.connect(*endpoint_iterator++, error);
}

is attempting to establish a connection to each endpoint until it succeeds or runs out of endpoints (thank you for the correction Eugen Constantin Dinca).

Marlon
  • 19,924
  • 12
  • 70
  • 101
  • 2
    Actually the `while` tries to connect to each endpoint until it succeeds or it runs out of endpoints. So at most 1 endpoint will be connected at the end of the loop. – Eugen Constantin Dinca Feb 24 '11 at 22:15
  • Why does it use *endpoint_iterator++ instead of endpoint_iterator++? Why would you need pointers? – Hami Feb 25 '11 at 22:18
  • 6
    @Hami `ip::tcp::resolver::iterator` is not a pointer, it just looks and behaves like one. The postfix increment operator (`operator++(int)`) gets the next iterator **after** the indirection operator (`operator*()`) obtains the underlying `endpoint` and returns it to `socket::connect()`. If the connection fails, `error` is set and the loop continues. These are the same concepts used by iterators in the Standard Template Library. – Sam Miller Feb 26 '11 at 17:22
  • To clarify @SamMiller 's comment, the increment operator is applied **before** the indirection operator (due to operator precedence rules), but it is returning the original iterator to the indirection operator due to the fact that `++` is a postfix operator. – pooya13 Jan 24 '19 at 18:18
  • 1
    iterator is deprecated in the laster version of boost, is there an alternative to this? – Srijan Chaudhary Jul 03 '20 at 05:03
  • 1
    @SrijanChaudhary You can use the following [function](https://www.boost.org/doc/libs/1_78_0/doc/html/boost_asio/reference/ip__basic_resolver/resolve/overload3.html) `auto const results = resolver.resolve(host, port);` – Ernie Sanderson Dec 27 '21 at 07:59