C++ boost::asio编程-域名解析详细介绍
发布时间:2020-12-14 23:51:10 所属栏目:C语言 来源:网络整理
导读:C++ boost::asio编程-域名解析 在网络通信中通常我们并不直接使用IP地址,而是使用域名。这时候我们就需要用reslover类来通过域名获取IP,它可以实现 与IP版本无关的网址解析。 #include "stdafx.h" #include "boost/asio.hpp" #include "boost/shared_ptr.hp
C++ boost::asio编程-域名解析 在网络通信中通常我们并不直接使用IP地址,而是使用域名。这时候我们就需要用reslover类来通过域名获取IP,它可以实现 #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; } 其中经过测试,端口可以填任意值均可以解析出来。 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |