C++|使用boost解析域名服务

【C++|使用boost解析域名服务】下面的源码给出了使用boost::asio进行域名解析的方法.

//g++ -g resolver_demo.cpp -o resolver_demo -lboost_system -lpthread //#include #include #include #include using namespace std; using namespace boost::asio; void resolv_connect(io_service& ios, ip::tcp::socket& sock, const char* host, int port){ ip::tcp::resolver rslv(ios); ip::tcp::resolver::query qry(host, boost::lexical_cast(port)); cout << "host_name: " << qry.host_name() << ", service_name: " << qry.service_name() << endl; ip::tcp::resolver::iterator iter = rslv.resolve(qry); ip::tcp::resolver::iterator end; boost::system::error_code ec = error::host_not_found; for( ; ec&&iter!=end; ++iter){ sock.close(); sock.connect(*iter, ec); }if(ec){ cout << "cannot connect" << endl; throw boost::system::system_error(ec); } else if(iter != end){ ip::tcp::endpoint endpoint = iter->endpoint(); cout << "query success!" << endl; cout << "host_ip: " << endpoint.address() << ", port: " << endpoint.port() << endl; } else return; }int main(){ try{ io_service ios; ip::tcp::socket sock(ios); resolv_connect(ios, sock, "news.sohu.com", 80); } catch(exception& e){ cerr << e.what() << endl; return 1; }return 0; }


下面是运行截图 C++|使用boost解析域名服务
文章图片


    推荐阅读