简体   繁体   中英

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:

  • 127.0.0.1
  • localhost
  • 192.168.1.255 (assuming the system is on a 192.168.1.0/24 subnet)
  • any of the IP addresses assigned to the current system's network interfaces
  • the system's local DNS name
  • any other loopback addresses that may be configured other than 127.0.0.1

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM