1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.vauth.foxyvpn.vpn
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.net.InetSocketAddress
import java.net.Socket
object PingUtil {
private const val TIMEOUT_MS = 1_500
suspend fun measureTcpLatencyMs(host: String, port: Int): Int? = withContext(Dispatchers.IO) {
withTimeoutOrNull(TIMEOUT_MS.toLong()) {
runCatching {
val start = System.nanoTime()
Socket().use { socket ->
socket.bind(InetSocketAddress(0))
com.vauth.foxyvpn.data.ControlPlaneHttp.socketProtector?.invoke(socket)
socket.connect(InetSocketAddress(host, port), TIMEOUT_MS)
}
((System.nanoTime() - start) / 1_000_000L).toInt()
}.onFailure {
com.vauth.foxyvpn.data.AppLogger.d("PingUtil", "ping failed to $host:$port: ${it.message}")
}.getOrNull()
}
}
}