当前位置:首页 > 通信资讯 > 正文

c++ boost asio(boost asio源码分析)

C++ boost::asio编程-域名解析

在网络通信中通常我们并不直接使用IP地址,而是使用域名。这时候我们就需要用reslover类来通过域名获取IP,它可以实现
与IP版本无关的网址解析。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 #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; }

其中经过测试,端口可以填任意值均可以解析出来。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。