Skip to content

Instantly share code, notes, and snippets.

@navopw
Last active February 14, 2019 12:31
Show Gist options
  • Save navopw/93edff217f4e5963b071ac5c55e0fbbe to your computer and use it in GitHub Desktop.
Save navopw/93edff217f4e5963b071ac5c55e0fbbe to your computer and use it in GitHub Desktop.
A method to determine the ping of a server in milliseconds in Java
/**
* A method to determine the ping of a server in milliseconds
* @param ip The ip address of the server you want to ping
* @param timeout The time window in which the destination has time to respond
* @return If the server is reachable within the timout it returns the ping time in ms, otherwise -1
* @throws IOException
*/
public static long pingServer(String ip, int timeout) throws IOException {
InetAddress address = InetAddress.getByName(ip);
long currentTime = System.currentTimeMillis();
boolean reachable = address.isReachable(timeout);
long endTime = System.currentTimeMillis() - currentTime;
return (reachable ? endTime : -1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment