DNS Reverse Lookup with Asio
Asked Answered
C

1

11

I would like to do a DNS reverse lookup (return hostname for a given IP Address) with asio, but I am not able to figure out which components I need to achieve this. Asio documentiation refers to ip::basic_resolver::resolve, but an endpoint_type is needed and I don't know how to use it.
Could someone please post or refer to an example?


EDIT:
With Joachim Pileborg's help I was able to accomplish the task. Needed code (Minumin without error handling):

#include <asio.hpp>
#include <string>
#include <iostream>

int main()
{
    asio::ip::address_v4 ipa = asio::ip::address_v4::from_string("8.8.8.8");    
    asio::ip::tcp::endpoint ep;
    ep.address(ipa);

    asio::io_service io_service;
    asio::ip::tcp::resolver resolver(io_service);
    asio::ip::tcp::resolver::iterator destination = resolver.resolve(ep);

    std::cout << destination->host_name() << std::endl;

    return 0;
}
Chivers answered 20/1, 2012 at 10:3 Comment(1)
Updated my answer with how to print all host names returned by the resolver.Jiles
J
12

I haven't used the resolver in Boost ASIO my self, but reading through the reference documentation it seems you shouldn't be using ip::basic_resolver directly. Instead you should use e.g. ip::tcp::resolver in which case the endpoint is an instance of ip::tcp::endpoint.

Edit

As each host can have multiple host names, the OPs solution could be extended like this:

asio::ip::tcp::resolver::iterator itr = resolver.resolve(ep);
asio::ip::tcp::resolver::iterator end;

for (int i = 1; itr != end; itr++, i++)
    std::cout << "hostname #" << i << ": " << itr->host_name() << '\n';
Jiles answered 20/1, 2012 at 10:20 Comment(3)
Interesting to see this, it's exactly what I am looking for, except that it doesn't seem to work. I have a DNS server running locally and it's responding 3 PTR records for a given IP address. I checked that with nslookup, dig and wireshark. Using Boost resolver I get only one entry. Debugging it step by step, I could see it simply calls getnameinfo(), which returns only one entry. Is there anything I am missing here?Acrylic
@ArthurPassos getnameinfo by design can only return one address. While the ASIO API supports multiple returns, there's actually no guarantee that it's actually implemented. You have to look at the actual ASIO source to see if there's any platform dependencies or other options to enable it.Jiles
At a first glance, I couldn't find it. By any chance, do you happen to know another way of performing such query?Acrylic

© 2022 - 2024 — McMap. All rights reserved.