Skip to content

Instantly share code, notes, and snippets.

@codebucketdev
Created July 5, 2014 11:20
Show Gist options
  • Save codebucketdev/d5c54253d520d7d34e1a to your computer and use it in GitHub Desktop.
Save codebucketdev/d5c54253d520d7d34e1a to your computer and use it in GitHub Desktop.
With this snippet you can ping a IP Address or Hostname in Java on Windows.
private InetAddress inet;
private long start;
private long end;
public PingTest(InetAddress inet)
{
this.inet = inet;
this.start = System.currentTimeMillis();
this.end = (this.start -1);
}
public void runCmd()
{
int timeout = 3800;
try
{
ProcessBuilder processBuilder = new ProcessBuilder(new String[] { "ping", inet.getHostAddress(), "-n", "1" });
Process process = processBuilder.start();
int processing = 0;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while (bufferedReader.readLine() != null)
{
processing++;
if(processing == 2)
{
this.start = System.currentTimeMillis();
}
else if(processing == 3)
{
this.end = System.currentTimeMillis();
}
}
if(calculatePingDelay() > timeout)
{
System.out.println("Cannot reached '" + inet.toString() + "'. Is your internet too slow?");
return;
}
System.out.println("Received response from '" + inet.toString() + "' in " + calculatePingDelay() + "ms");
bufferedReader.close();
}
catch (IOException ex)
{
System.err.println("Error while connecting to '" + inet.toString() + "'");
ex.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment