Boost.Asioでは、resolverというクラスを使用することにより、google.comのような名前から、IPアドレスに変換することができます。
ip::tcp::resolver resolver(io_service); ip::tcp::resolver::query query("google.com", "http"); resolver.async_resolve(query, on_resolve);
以下サンプル
#include <boost/asio.hpp> #include <boost/bind.hpp> #include <iostream> namespace asio = boost::asio; namespace ip = asio::ip; class Client { asio::io_service& io_service_; ip::tcp::resolver resolver_; public: Client(asio::io_service& io_service) : io_service_(io_service), resolver_(io_service) { ip::tcp::resolver::query query("google.com", "http"); resolver_.async_resolve(query, boost::bind(&Client::on_resolve, this, asio::placeholders::error, asio::placeholders::iterator)); } private: void on_resolve(const boost::system::error_code& error, ip::tcp::resolver::iterator endpoint_iterator) { if (error) { std::cout << error.message() << std::endl; } else { ip::tcp::resolver::iterator end; for (; endpoint_iterator != end; ++endpoint_iterator) { std::cout << endpoint_iterator->endpoint().address().to_string() << std::endl; } } } }; int main() { asio::io_service io_service; Client client(io_service); io_service.run(); }
66.249.89.99 66.249.89.104
Boost.Asioの接続関数には名前解決されたendpoint iteratorを間接参照して渡します。
socket.async_connect(*endpoint_iterator, on_connect);
以下サンプル:
#include <boost/asio.hpp> #include <boost/bind.hpp> #include <iostream> namespace asio = boost::asio; namespace ip = asio::ip; class Client { asio::io_service& io_service_; ip::tcp::resolver resolver_; ip::tcp::socket socket_; public: Client(asio::io_service& io_service) : io_service_(io_service), resolver_(io_service), socket_(io_service) { ip::tcp::resolver::query query("google.com", "http"); resolver_.async_resolve(query, boost::bind(&Client::on_resolve, this, asio::placeholders::error, asio::placeholders::iterator)); } private: void on_resolve(const boost::system::error_code& error, ip::tcp::resolver::iterator endpoint_iterator) { if (error) { std::cout << "cannot resolve: " << error.message() << std::endl; } else { std::cout << "success resolve" << std::endl; socket_.async_connect(*endpoint_iterator, boost::bind(&Client::on_connect, this, asio::placeholders::error)); } } void on_connect(const boost::system::error_code& error) { if (error) { std::cout << "cannot connect: " << error.message() << std::endl; } else { std::cout << "success connect" << std::endl; } } }; int main() { asio::io_service io_service; Client client(io_service); io_service.run(); }