Home >Backend Development >C#.Net Tutorial >C++ boost::asio programming-detailed introduction to domain name resolution

C++ boost::asio programming-detailed introduction to domain name resolution

黄舟
黄舟Original
2016-12-14 16:58:292144browse

C++ boost::asio Programming-Domain Name Resolution

In network communication, we usually do not use IP addresses directly, but domain names. At this time, we need to use the reslover class to obtain the IP through the domain name, which can realize URL resolution independent of the IP version.

#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; 
}

After testing, the port can be filled with any value and can be parsed.

Thanks for reading, I hope it can help everyone. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn