Correct way to look up Hostnames in Qt with QHostInfo or QDnsLookUp

2.6k views Asked by At

I am trying to use QHostInfo or QDnsLookUp to look up a hostname and get a list of QHostAddress. I would prefer QHostInfo (the interface is simpler) but I tried also QDnsLookUp.

In the first case, I use QHostInfo::lookupHost() static function, and then I get the addresses from the result with QHostInfo::addresses()

In the second case I use QDnsLookup::lookup(), with the type set to QDnsLookup::A (IPv4 address records) and I get the results with QDnsLookup::hostAddressRecords() (and I get the value of the QDnsHostAddressRecord elements).

Well, both methods work somehow, but I get only one result...in both cases it should be a list of results from the documentation...but my list contains only one element...

Is there some option or something else that I should set to get the complete list? What could have gone wrong?

2

There are 2 answers

0
n3mo On BEST ANSWER

With the help of Dig - Google Apps I found out that the QDnsLookup::A option was not the correct solution. I have to use QDnsLookup::ANY in order to have a complete list.

3
Mohammad Kanan On

You need to store result in a list, some examples:

QString myClass::getBroadWiFiAddress()
{
    QString ipAddress;
    QNetworkInterface wifi;
    // Get WiFi interface
     QList<QNetworkInterface> interfceList = QNetworkInterface::allInterfaces();
     for (int i = 0; i < interfceList.size(); ++i)
     {

         if (interfceList.at(i).name().contains("wireless") && interfceList.at(0).isValid() && interfceList.at(i).IsUp)
         {
             //qDebug() << "Interfaces:" << i << interfceList.at(i).name() << " / " << interfceList.at(i).humanReadableName();
             wifi = interfceList.at(i);
            break;
         }

     }

    QList<QHostAddress> ipAddressesList = wifi.allAddresses();
    // use the first non-localhost IPv4 address
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address() ) {
            ipAddress = ipAddressesList.at(i).toString();
            //qDebug() << "Using following IP Address:" << ipAddress;
            break;
        }
    }
    //qDebug() << "getBroadWiFiAddress" << ipAddress;
    return ipAddress;
}