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
    }

在此 做个笔记

相关推荐
hai_android4 分钟前
不用 AIDL,手把手教你手写 Binder 代理类
android·kotlin
星恒讯工业路由器5 分钟前
房车旅居不“断网”:移动生活如何实现全程在线?
网络·物联网·生活·工业路由器·车载工业路由器·房车通信·双卡备份
吴声子夜歌24 分钟前
ApacheCommons——commons-text(模板替换与文本算法)
java·开发语言·算法·apache
Haooog38 分钟前
Agent 开发中的 Memory:State、短期记忆、长期记忆与 Memory Retrieval
java·agent·memory
砚底藏山河1 小时前
【量化纯GET实战 #23】多股票相关性:用收益率看板块联动
java·数据库·python·金融·数据分析
抠脚小弟1 小时前
Spring Cache 使用详解:从入门到实战
java·spring
和裕1 小时前
光伏储能定制加强型瓦楞纸箱:降低组件运输隐裂率与售后损耗的核心价值
大数据·运维·网络·人工智能·算法
ZGG0031 小时前
MySQL 索引详解:B+ 树、聚簇索引与最左前缀
java·数据库·mysql
萧瑟余晖1 小时前
Java深入解析篇五十四之对象模型详解
java·开发语言
乐维_lwops2 小时前
网管系统:流量分析如何用“五元组”+“TOPN”透视网络异常?
网络·流量分析·网管系统