C++ boost::asio Programming-Domain Name Resolution
In network communication, we usually do not use IP addresses directly, but domain names. At this time, we need to use the reslover class to obtain the IP through the domain name, which can realize URL resolution independent of the IP version.
#include "stdafx.h" #include "boost/asio.hpp" #include "boost/shared_ptr.hpp" #include "boost/thread.hpp" #include <boost/lexical_cast.hpp>//使用字符串转换功能 using namespace std; using namespace boost::asio; #ifdef _MSC_VER #define _WIN32_WINNT 0X0501 //避免VC下编译警告 #endif //域名解析为IP //入参:域名,端口 //返回:ip地址 vector<string> domain2ip(const char *domain,int port) { io_service ios; //创建resolver对象 ip::tcp::resolver slv(ios); //创建query对象 ip::tcp::resolver::query qry(domain,boost::lexical_cast<string>(port));//将int型端口转换为字符串 //使用resolve迭代端点 ip::tcp::resolver::iterator it=slv.resolve(qry); ip::tcp::resolver::iterator end; vector<string> ip; for(;it!=end;it++) { ip.push_back((*it).endpoint().address().to_string()); } return ip; } int _tmain(int argc, _TCHAR* argv[]) { vector<string> ip=domain2ip("www.csdn.net",0); for(int i=0;i<ip.size();i++) { cout<<ip[i]<<endl; } getchar(); return 0; }