kotlin用ping命令判断网络是否是通的

ping通的报文:

ping -c 3 -W 1 127.0.0.5

PING 127.0.0.5 (127.0.0.5) 56(84) bytes of data.

64 bytes from 127.0.0.5: icmp_seq=1 ttl=64 time=0.105 ms

64 bytes from 127.0.0.5: icmp_seq=2 ttl=64 time=0.077 ms

64 bytes from 127.0.0.5: icmp_seq=3 ttl=64 time=0.069 ms

--- 127.0.0.5 ping statistics ---

3 packets transmitted, 3 received, 0% packet loss, time 2042ms

rtt min/avg/max/mdev = 0.069/0.083/0.105/0.018 ms

不通的报文:

ping -c 3 -W 1 192.168.0.5

PING 192.168.0.5 (192.168.0.5) 56(84) bytes of data.

--- 192.168.0.5 ping statistics ---

3 packets transmitted, 0 received, 100% packet loss, time 2021ms

复制代码
private fun ping(ip:String): Boolean {

        val arr = arrayOf("sh", "-c", "ping -c 2 -W 1 $ip")//192.168.0.1

        val process = Runtime.getRuntime().exec(arr)
        val input =  BufferedReader(InputStreamReader(process.inputStream));
        var connectedCount = 0
        var line: String? = null
        input.use {
            try {
                while (input.readLine().also { line = it } != null) {
                    val result = getCheckResult(line!!)
                    connectedCount += result

                    LogHelper.d("MainActivity --- connectedCount = $connectedCount result = $result line = $line")
                    if(connectedCount > 0){
                        return true;
                    }
                }
            }catch (e:Exception){
                e.printStackTrace()
                return false
            }

        }

        return connectedCount > 0

    }


    private fun getCheckResult(line: String): Int {
        return if ((line.contains("ttl=") || line.contains("TTL=")) && line.contains("ms")) {
            1
        } else 0
    }

在此 做个笔记

相关推荐
码路飞4 小时前
GPT-5.3 Instant 终于学会好好说话了,顺手对比了下同天发布的 Gemini 3.1 Flash-Lite
java·javascript
SimonKing4 小时前
OpenCode AI编程助手如何添加Skills,优化项目!
java·后端·程序员
Kapaseker6 小时前
一杯美式搞定 Kotlin 空安全
android·kotlin
Seven976 小时前
剑指offer-80、⼆叉树中和为某⼀值的路径(二)
java
怒放吧德德17 小时前
Netty 4.2 入门指南:从概念到第一个程序
java·后端·netty
雨中飘荡的记忆19 小时前
大流量下库存扣减的数据库瓶颈:Redis分片缓存解决方案
java·redis·后端
心之语歌21 小时前
基于注解+拦截器的API动态路由实现方案
java·后端
华仔啊1 天前
Stream 代码越写越难看?JDFrame 让 Java 逻辑回归优雅
java·后端
ray_liang1 天前
用六边形架构与整洁架构对比是伪命题?
java·架构
FunnySaltyFish1 天前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack