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
    }

在此 做个笔记

相关推荐
云飞云共享云桌面1 小时前
替代传统电脑的共享云服务器如何实现1拖8SolidWorks设计办公
linux·运维·服务器·网络·电脑·制造
没有bug.的程序员1 小时前
分布式架构未来趋势:从云原生到智能边缘的演进之路
java·分布式·微服务·云原生·架构·分布式系统
RollingPin2 小时前
iOS八股文之 网络
网络·网络协议·ios·https·udp·tcp·ios面试
毕业设计制作和分享3 小时前
springboot150基于springboot的贸易行业crm系统
java·vue.js·spring boot·后端·毕业设计·mybatis
惘嘫、冋渞7 小时前
AWS同一账号下创建自定义VPC并配置不同区域的对等链接
网络·云计算·aws
小梁努力敲代码8 小时前
java数据结构--List的介绍
java·开发语言·数据结构
摸鱼的老谭8 小时前
构建Agent该选Python还是Java ?
java·python·agent
云知谷9 小时前
【HTML】网络数据是如何渲染成HTML网页页面显示的
开发语言·网络·计算机网络·html
lang201509289 小时前
Spring Boot 官方文档精解:构建与依赖管理
java·spring boot·后端
夫唯不争,故无尤也9 小时前
Tomcat 启动后只显示 index.jsp,没有进入你的 Servlet 逻辑
java·servlet·tomcat