Android Get the Ping value of the IP address NetworkPingUtils

In the project, I need to ping the dynamically configured IP list to determine the delay, take out the three smallest ones, randomly select values, and then connect. I finally figured it out after spending an afternoon!

Requirements realization ideas:

1. Find a way to ping the IP address;

2. Ping at the same time without letting the user wait;

3. Sort according to the obtained ping list, and take the top three addresses and return them randomly;

3. Wait synchronously, obtain the minimum ping value IP, and then perform the following operations.

Core methods:

private fun pingIP(ip: String): PingBean {
        val command = "ping -c 1 -W 1 $ip"
        val proc = Runtime.getRuntime().exec(command)
        val reader = BufferedReader(InputStreamReader(proc.inputStream))
        if (proc.waitFor() == 0) {
            val result = StringBuilder()
            while (true) {
                val line = reader.readLine() ?: break
                result.append(line).append("\n")
            }
            Timber.tag(AppConstant.TAG).e("ping OK")
            return PingBean(ip, getPing(result.toString()))//getPing()方法在后面,是获取平均延迟。
        }
        return PingBean(ip, 10000.0)
    }

Detailed code explanation: Parameters: Pass in the IP address Return value: Return the IP and the obtained delay. getPing() obtains the average delay.

The first command represents the computer instruction to be executed. You can directly get this instruction to the console to execute it.

-c represents the number of times, -W represents the timeout.

The above means: 10 data packets have been sent, 10 data have been received, 0.0% data packet loss, 10 data exceeds the waiting time 

The following min/avg/max/stddev = 39.420/45.341/47.971/3.133 ms minimum delay/average/maximum/standard deviation (the smaller the standard deviation, the better)

Guess you like

Origin blog.csdn.net/LoveFHM/article/details/129150372