直接上代码: fun ping(): String { var result: String? = null try { val ip = "www.baidu.com" val p = Runtime.getRuntime().exec("ping -c 3 -w 100 $ip") //ping3次 // 读取ping的内容,可不加。 val input = p.inputStream val `in` = BufferedReader(InputStreamReader(input)) val stringBuffer = StringBuffer() var content: String? = "" while (`in`.readLine().also { content = it } != null) { stringBuffer.append(content) } Log.i("TTT", "result content : $stringBuffer") // PING的状态 val status = p.waitFor() if (status == 0) { result = "成功~" return result } else { result = "失败~无法到达IP地址" } } catch (e: IOException) { result = "failed~ IOException" } catch (e: InterruptedException) { result = "failed~ InterruptedException" } finally { Log.i("TTT", "result = $result") } return "失败~无法连接IP地址" }