c++networkingboost-asio

Why is port number given when doing a DNS lookup?


In ASIO C++ networking library you can resolve an address by creating a query object, whose constructor takes (optionally whether it's ip4 or ip6), a "host" argument and a "service" argument. The "host" is the name of the site you want to resolve to an IP number, and the "service" (I'm guessing) is the port number. So this does a DNS lookup/request, but my understanding is that DNS queries are for looking up associations between names and IP numbers, I don't see how the port figures into this at all.

asio::ip::tcp::resolver::query query{"www.google.com", "80"};

Adding further to my befuddlement, there's a "query" constructor that takes just the "service". The comment gives a little explanation:

This constructor is typically used to perform name resolution for local service binding

I don't understand, I thought DNS lookups were for strictly for (name -> IP number) mappings. If I resolve a name with port 109 and then the same name with port 400, do I get back the same IP numbers?


Solution

  • The port doesn't do anything for the name lookup; it's just there so the result of a successful lookup is a ready-to-use endpoint that you can connect to because it already has the port number.

    Also, the system might have a file like /etc/services, which assigns names to ports. It's likely (although I've never tried it) that the resolver uses this so you could just give https as "service" instead of 443. I think it's too risky to rely on that, though.

    The pointless distinction between tcp::resolver and udp::resolver plays into the same area: it allows the resolver to return tcp::endpoint or udp::endpoint (even though they contain exactly the same data...), and also helps with the "services" file lookup.