Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a host name in to a boost address or endpoint?

Tags:

c++

boost

I'm using a C++ Redis Library on top of Boost. (https://github.com/nekipelov/redisclient)

To connect, I have to give it either a single tcp endpoint:

boost::asio::ip::tcp::endpoint

Or an address + port

boost::asio::ip::address, unsigned short

Currently, I started with:

boost::asio::ip::address address = boost::asio::ip::address::from_string(someIPVariable);

and passed that along with the port, it worked fine and connected. However, I now need to do it by hostname instead of IP. If I simply put the host name in to the line above, it throws an exception as I think it expects an IP address.

I'm used to specifying connections as just ("IP OR Hostname", port) so I'm a little unsure what's required here. I checked the constructors for both to see if any could convert a host name + port to what was required, but I can't find anything.

like image 777
mGuv Avatar asked Jul 09 '15 10:07

mGuv


1 Answers

You need to use a tcp::resolver to do name resolution (i.e. DNS lookup):

boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::query query("example.com", "80");
boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query);

Dereferencing the iterator gives you a resolver entry that has a tcp::endpoint:

boost::asio::ip::tcp::endpoint endpoint = iter->endpoint();
like image 199
Jonathan Wakely Avatar answered Oct 20 '22 00:10

Jonathan Wakely