Test if address is reachable before choosing

This commit is contained in:
Andrius Dagys
2017-04-20 15:47:07 +01:00
committed by Mike Hearn
parent a01c466beb
commit a2de90a6da

View File

@ -4,12 +4,16 @@ import java.net.InetAddress
import java.net.NetworkInterface import java.net.NetworkInterface
object AddressUtils { object AddressUtils {
private val REACHABLE_TIMEOUT_MS = 1000
/** Returns the first public IP address found on any of the network interfaces, or `null` if none found. */ /** Returns the first public IP address found on any of the network interfaces, or `null` if none found. */
fun tryDetectPublicIP(): InetAddress? { fun tryDetectPublicIP(): InetAddress? {
for (int in NetworkInterface.getNetworkInterfaces()) { for (int in NetworkInterface.getNetworkInterfaces()) {
if (int.name.startsWith("utun")) continue if (int.isLoopback) continue
for (address in int.inetAddresses) { for (address in int.inetAddresses) {
if (isPublic(address)) return address if (isPublic(address) && address.isReachable(REACHABLE_TIMEOUT_MS))
return address
} }
} }
return null return null