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
    }

在此 做个笔记

相关推荐
小李独爱秋21 分钟前
计算机网络经典问题透视:在浏览器中应当有几个可选解释程序?
服务器·网络·网络协议·tcp/ip·计算机网络
Knight_AL27 分钟前
Spring AOP 中 JoinPoint 使用指南
java·python·spring
jmxwzy32 分钟前
点赞系统问题
java·redis·tidb·pulsar
ss27335 分钟前
ThreadPoolExecutor:自定义线程池参数
java·开发语言
invicinble1 小时前
关于fastjson的具体使用案例
java
yenggd1 小时前
华为批量下发配置命令使用telnetlib模块
网络·python·华为
墨着染霜华1 小时前
Spring Boot整合Kaptcha生成图片验证码:新手避坑指南+实战优化
java·spring boot·后端
码界奇点1 小时前
Java外功核心7深入源码拆解Spring Bean作用域生命周期与自动装配
java·开发语言·spring·dba·源代码管理
czlczl200209251 小时前
Spring Security @PreAuthorize 与自定义 @ss.hasPermission 权限控制
java·后端·spring
G_H_S_3_1 小时前
【网络运维】企业级监控平台Zabbix:部署与实践指南
linux·运维·网络·zabbix