In my game app, I call this:
Runtime.getRuntime().exec("/system/bin/ping -c 1 -w 1 $serverip")
It gives an accurate reading of the ping to my server but in some exceptional cases, the ping doesn't go through in certain circumstances (for example, when the player is using Mobile Data, the command returns nothing in 25% of the cases for no apparent reason).
I am aware there must be other ping commands/functions/methods/protocols to get a ping reading (I am not sure what game companies use in order to get constant ping readings inside their games), any suggestions ? Thanks in advance.
You could also use the Socket class provided in the java.net package. Using the provided method connect(SocketAddress endpoint) you can connect your socket to the server.
For example, you can use something like this
public static boolean ping(String address, int port) {
Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress(address, port));
} catch (IOException e) {
return false;
} finally {
try {
socket.close();
} catch (IOException ignored) { }
}
return true;
}
You can invoke like this ping("www.google.com", 443)
Finally, you could use the java.net.URL class to wrap your String url. For instance,
URL url = new URL("https://www.google.com:443/");
ping(url.getHost(), url.getPort());