Bri Bri
Bri Bri

Reputation: 2268

C++ / Qt: How can I detect when a hostname or IP address refers to the current system?

I'm writing a macOS C++ application using Qt that acts as both a UDP client and UDP server. The server functionality allows the user to configure which port the UDP packets will be received on, and the client functionality allows specifying both a target host and a port number. The host can be either a hostname or an IP address, including addresses or hostnames that resolve to a multicast or broadcast address.

In order to help prevent circularity, when the server functionality is enabled I need to be able to warn the user when the host and port they've entered for the client would send the packets directly to the app's server. Of course it's easy to check if the port numbers match, but this means I need to know whether the host they've entered refers to the current system.

Examples of hostnames or IP addresses that would typically be problematic:

How could I go about detecting this?

Since this app is being written using Qt, a solution that exclusively uses Qt's framework would be ideal. But if that's not possible (since Qt doesn't handle every possible use case) a macOS-specific solution will work too.

Upvotes: 0

Views: 1092

Answers (1)

Soheil Armin
Soheil Armin

Reputation: 2795

QNetworkInterface class should provide the most information you may need. You can obtain a list of IP addresses using QNetworkInterface::allAddresses() static function.

You can also get a list of all interfaces using QNetworkInterface::allInterfaces().

Calling QNetworkInterface::addressEntries() for each QNetworkInterface returned by QNetworkInterface::allInterfaces() will give you more information about address entries for each interface.

auto ifs = QNetworkInterface::allInterfaces();
foreach (auto interface , ifs){
    auto addresses = interface.addressEntries();
    foreach ( auto addy , addresses){
        ///play with the addy here.
    }
}

You can also test hostnames against those ip addresses which you are going to ban, using QDnsLookup class.

Upvotes: 2

Related Questions