Boost.asio 之resolver类
1.resolver类
通过域名获得可用的IP,可实现与IP版本无关的网址解析
2.resolver是basic_resolver的tcp协议特化
3.内部类
query和iterator
4.查询IP地址
resolver,query,iterator
5.通过域名获得可用IP步骤
- 创建qurey对象
- resolve()成员函数生成iterator对象,iterator对象代表查询到的ip端点
- socket对象尝试连接,直到找到一个可用的IP
demo
#pragma once #include <iostream> #include <boost/asio.hpp> #include <boost/system/error_code.hpp> #include <boost/asio/ip/address.hpp> #include <boost/lexical_cast.hpp> #include <string> using namespace boost::asio; class client { public: virtual ~client(); typedef ip::tcp::socket socket_type;
private: io_service m_io;//web socket_type m_sock; public:
client(const char * name, int iport) : m_sock(m_io) { resolve_connect(m_sock, name, iport); }
void resolve_connect(ip::tcp::socket &sock, const char * name, int port); };
#include "pch.h" #include "client.h" client::~client() { } void client::resolve_connect(ip::tcp::socket &sock, const char * name, int port) { ip::tcp::resolver r(sock.get_io_service()); ip::tcp::resolver::query q(name, boost::lexical_cast<std::string>(port)); //query对象构造:域名和端口号
//ip::tcp::resolver::query q("127.0.0.1", "http"); //query对象构造:IP地址和服务名
auto iter = r.resolve(q); decltype(iter) end; boost::system::error_code ec = error::host_not_found; for (; ec && iter != end; ++iter) { sock.close(); sock.connect(*iter, ec); } if (ec) { std::cout << "can't connect." << std::endl; throw boost::system::system_error(ec); } std::cout << "connect success." << std::endl; std::cout << m_sock.remote_endpoint().address() << std::endl; }
// WebClient.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include "pch.h" #include <iostream> #include "client.h" int main() { try { std::cout << "web client start." << std::endl; client cl("www.baidu.com", 80); } catch (const std::exception& ec) { std::cout << ec.what() << std::endl; } getchar(); std::cout << "Hello World!\n"; }

浙公网安备 33010602011771号