Android ping域名示例代码

private val regex = Regex("""time=([\d.]+)""")

    /**
     * @return Pair(Boolean,Int) boolean为ping是否成功 int为ping的具体数值
     */
    private fun ping(host: String): Pair<Boolean, Int> {
        val command = "ping -c 1 -i 0.2 -W 2 $host"
        var networkTimeResult = -1
        try {
            val process = Runtime.getRuntime().exec(command)
            val reader = BufferedReader(InputStreamReader(process.inputStream))
            var line = reader.readLine()
            while (line != null) {
                if (line.contains("time")) {
                    val matchResult = regex.find(line)
                    val networkTime = matchResult?.groupValues?.getOrNull(1)
                    if (networkTime != null) {
                        //四舍五入
                        networkTimeResult = networkTime.toDouble().roundToInt()
                        return Pair(networkTimeResult != -1, networkTimeResult)
                    }
                }
                line = reader.readLine()
            }
            return Pair(false, -1)
        } catch (e: Exception) {
            e.printStackTrace()
            return Pair(false, -1)
        }
    }

PS:补充不同平台上的ping命令,不过注意,上面代码的正则可能不适用window,可能要改下

//linux或mac系统 (Android也视为linux)
val cmd = "ping -c 1 $host"

//window系统
val cmd = "ping -n 1 $host"
posted @ 2024-12-04 10:38  Stars-one  阅读(6)  评论(0编辑  收藏  举报