Created
July 5, 2014 11:20
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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