Getting all IP addresses in Qt

In a network application written in Qt, if you want to get all IP addresses on the host machine, you can use QNetworkInterface::allAddresses(). But please bear in mind that this function only returns the addresses of interfaces whose link are UP, as stated in Qt Docs:

This convenience function returns all IP addresses found on the host machine. It is equivalent to calling addressEntries() on all the objects returned by allInterfaces() that are in the QNetworkInterface::IsUp state to obtain lists of QNetworkAddressEntry objects then calling QNetworkAddressEntry::ip() on each of these.

So based on this description, if you want to get all IP addresses including the link down ones, you can use a function as below:

QList<QHostAddress> allAddresses()
    const QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    QList<QHostAddress> result;
    for (const auto& p : interfaces)
        for (const QNetworkAddressEntry& entry : p.addressEntries())
            result += entry.ip();

    return result;

This function derives from the definition of QNetworkInterface::allAddresses() in qnetworkinterface.cpp, but simply removes the check of QNetworkInterface::IsUp flag of the interface.

Have fun!

comments powered by Disqus