C++ boost::asio編程-域名解析詳細(xì)介紹
C++ boost::asio編程-域名解析
在網(wǎng)絡(luò)通信中通常我們并不直接使用IP地址,而是使用域名。這時(shí)候我們就需要用reslover類(lèi)來(lái)通過(guò)域名獲取IP,它可以實(shí)現(xiàn)
與IP版本無(wú)關(guān)的網(wǎng)址解析。
#include "stdafx.h" #include "boost/asio.hpp" #include "boost/shared_ptr.hpp" #include "boost/thread.hpp" #include <boost/lexical_cast.hpp>//使用字符串轉(zhuǎn)換功能 using namespace std; using namespace boost::asio; #ifdef _MSC_VER #define _WIN32_WINNT 0X0501 //避免VC下編譯警告 #endif //域名解析為IP //入?yún)ⅲ河蛎?,端? //返回:ip地址 vector<string> domain2ip(const char *domain,int port) { io_service ios; //創(chuàng)建resolver對(duì)象 ip::tcp::resolver slv(ios); //創(chuàng)建query對(duì)象 ip::tcp::resolver::query qry(domain,boost::lexical_cast<string>(port));//將int型端口轉(zhuǎn)換為字符串 //使用resolve迭代端點(diǎn) 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; }
其中經(jīng)過(guò)測(cè)試,端口可以填任意值均可以解析出來(lái)。
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
用C++實(shí)現(xiàn)一個(gè)命令行進(jìn)度條的示例代碼
這篇文章主要介紹了用C++實(shí)現(xiàn)一個(gè)命令行進(jìn)度條的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04Matlab利用prim算法實(shí)現(xiàn)迷宮的生成
普里姆算法(Prim算法),圖論中的一種算法,可在加權(quán)連通圖里搜索最小生成樹(shù)。本文將利用prim算法迷宮生成及其藝術(shù)渲染,感興趣的可以了解一下2022-10-10Qt利用QState狀態(tài)機(jī)實(shí)現(xiàn)控件互斥操作詳解
這篇文章主要為大家詳細(xì)介紹了Qt如何利用QState狀態(tài)機(jī)實(shí)現(xiàn)控件互斥操作,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-12-12