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; } |
其中經過測試,端口可以填任意值均可以解析出來。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!