boost::asio编程-域名解析

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

与IP版本无关的网址解析。

#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;
}
其中经过测试,端口可以填任意值均可以解析出来。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值