使用boost解析域名服务

时间:2022-09-08 23:51:57

下面的源码给出了使用boost::asio进行域名解析的方法.

//g++ -g resolver_demo.cpp -o resolver_demo -lboost_system -lpthread
//

#include <iostream>
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
#include <boost/lexical_cast.hpp>

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<string>(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;
}

下面是运行截图

使用boost解析域名服务