Get local active IP address
The active IP address would be the one actually used to communicate on the network. In most cases a PC has the ethernet port used as primary and the wifi network used as secondary (or vice versa). If you switch from one to the other you create a situation where both network devices have a valid IP but only one of the two is actually used based on the active connection at that time.
There may be cases where you need to know which IP is actually the active one used to communicate on the network. The following function returns the active IP:
QString getLocalIpAddress() { QUdpSocket socket; QString ip; socket.connectToHost("8.8.8.8", 80); ip = socket.localAddress().toString(); socket.disconnectFromHost(); return ip; }
Please note that even if an external IP is set (8.8.8.8) there is no need for the network to be connected to Internet. Since it is a UDP communication, the IP is only used as a reference and even if the connection fails, the local IP is still detected correctly.
Comments
Post a Comment