DNS query

The resolver class is used to do DNS query, i.e., convert a host+service to IP+port. Take boost::asio::ip::tcp::resolver as an example:

  1. #include <boost/asio.hpp>
  2. #include <iostream>
  3. int main()
  4. {
  5. try
  6. {
  7. boost::asio::io_context io_context;
  8. boost::asio::ip::tcp::resolver resolver{io_context};
  9. boost::asio::ip::tcp::resolver::results_type endpoints =
  10. resolver.resolve("google.com", "https");
  11. for (auto it = endpoints.cbegin(); it != endpoints.cend(); it++)
  12. {
  13. boost::asio::ip::tcp::endpoint endpoint = *it;
  14. std::cout << endpoint << '\n';
  15. }
  16. }
  17. catch (std::exception& e)
  18. {
  19. std::cerr << e.what() << '\n';
  20. }
  21. return 0;
  22. }

The running result is:

  1. 74.125.24.101:443
  2. 74.125.24.139:443
  3. 74.125.24.138:443
  4. 74.125.24.102:443
  5. 74.125.24.100:443
  6. 74.125.24.113:443

The element of boost::asio::ip::tcp::resolver::results_type‘s every iteration is basic_resolver_entry:

  1. template <typename InternetProtocol>
  2. class basic_resolver_entry
  3. {
  4. ......
  5. public:
  6. /// The protocol type associated with the endpoint entry.
  7. typedef InternetProtocol protocol_type;
  8. /// The endpoint type associated with the endpoint entry.
  9. typedef typename InternetProtocol::endpoint endpoint_type;
  10. ......
  11. /// Convert to the endpoint associated with the entry.
  12. operator endpoint_type() const
  13. {
  14. return endpoint_;
  15. }
  16. ......
  17. }

Since it has endpoint_type() operator, it can be converted to endpoint directly:

  1. boost::asio::ip::tcp::endpoint endpoint = *it;