How to make ASIO resolve IP address without knowing the service/port?

Viewed 433

How could I get ASIO to resolve a domain name without supplying the port/service name?

As far as I know, ASIO requires a port number or service name while resolving. Why? How would I do something like nslookup example.com? And not supplying the service name simply makes ASIO generate the error "tcp::resolver: service not found".

(And other answers on SO didn't help. It resolved the name from an address. But I want the other way arround.)

1 Answers

I would pass an arbitrary service port. Like "1". And just ignore that.

To be very purist you can tell the query that the service need not be resolved:

#include <boost/asio.hpp>
#include <iostream>

int main() {
    using boost::asio::ip::tcp;
    using query = tcp::resolver::query;

    query q("www.example.com", "1", query::numeric_service);
    tcp::resolver r(boost::asio::system_executor{});

    for (auto ep : r.resolve(q)) {
        std::cout << ep.endpoint().address() << "\n";
    }
}

On my box, it prints:

93.184.216.34
[2606:2800:220:1:248:1893:25c8:1946]

There are more flags available, so you could look at the documentation for them (e.g. to resolve CNAME records).

Related