C + + Boost::asio programming-domain name resolution
In the network communication, we usually do not use the IP address directly, but use the domain name. At this time we need to use the Reslover class to get the IP through the domain name, it can realize
URL resolution that is independent of the IP version.
#include "stdafx.h" #include "boost/asio.hpp" #include "boost/shared_ptr.hpp" #include "boost/thread.hpp" #include &l
t;boost/lexical_cast.hpp>//uses the string conversion function using namespace std;
using namespace Boost::asio; #ifdef _msc_ver #define _WIN32_WINNT 0x0501//Avoid VC compiler warning #endif//Domain name resolution for IP//Entry parameters: Domain name, port//return: IP address vector<string> ;
DOMAIN2IP (const char *domain,int port) {Io_service iOS;
Create resolver Object Ip::tcp::resolver SLV (iOS); Create the Query Object Ip::tcp::resolver::query qry (domain,boost::lexical_cast<string> (port));//convert int port to string//
Use the Resolve Iteration endpoint 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;
}
After testing, the port can be filled out any value can be resolved.
Thank you for reading, I hope to help you, thank you for your support for this site!