Reputation: 1396
I am making a pinging app on Android as part of a practice project and I am quite stuck doing the real "pinging" thing. I have dug around the stack looking for a "Kotlin" way to do it since I am very new to this. But I ended up finding only Java code like this:
private boolean executeCommand(){
System.out.println("executeCommand");
Runtime runtime = Runtime.getRuntime();
try
{
Process mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int mExitValue = mIpAddrProcess.waitFor();
System.out.println(" mExitValue "+mExitValue);
if(mExitValue==0){
return true;
}else{
return false;
}
}
catch (InterruptedException ignore)
{
ignore.printStackTrace();
System.out.println(" Exception:"+ignore);
}
catch (IOException e)
{
e.printStackTrace();
System.out.println(" Exception:"+e);
}
return false;
}
I tried recreating it in Kotlin but everything turns to red in my IDE. I know it's not easy work but I would really appreciate if you guys helped me find a direct way to ping a host then retrieve the ping value.
Upvotes: 1
Views: 5088
Reputation: 1
class PingUtil {
fun execute(address: String, options: String): String {
// options with -c is number of repetitions, -t is time to live ( with ttl you can implement tracert functionality by iteratively increasing ping, increasing ttl after each iteration )
return try {
Runtime.getRuntime().exec("ping $options $address").inputStream.bufferedReader()
.use { it.readText() }
} catch (e: IOException) {
Log.e("PingUtility", "An error occurred while performing a ping", e)
"N/A"
}
}
}
With command line "ping -c 1 hi.fpt.vn", the response will look like: this
After that, u can use regex to get domain, ip address, response time
Upvotes: 0
Reputation: 97140
Considering that a ping is just an ICMP ECHO
request, I think the easiest way to do that would just be to use InetAddress.isReachable()
.
According to the Javadoc:
public boolean isReachable (int timeout)
Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible.
Android implementation attempts ICMP ECHO REQUESTs first, on failure it will fall back to TCP ECHO REQUESTs. Success on either protocol will return true.
Upvotes: 3