How can I check whether my computer is connected to the Internet. I don't want to use URL check method. Is it possible to call an operating system's function using java? For example, in JNA library, is there any function to perform this ?
2 Answers
You can use ping command like this:
class PingHost
{
public static void main(String[] args)
{
String ip = "www.google.com";
String pingResult = "";
String pingCmd = "ping " + ip;
try
{
Runtime r = Runtime.getRuntime();
Process p = r.exec(pingCmd);
BufferedReader in = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
pingResult += inputLine;
}
in.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
You should receive a response like:
64 bytes from 173.194.37.147: icmp_seq=0 ttl=52 time=299.032 ms
64 bytes from 173.194.37.147: icmp_seq=1 ttl=52 time=508.100 ms
6 Comments
fivetech
Thanks for reply but I am going to use this feature in a Thread. Program should check the connection per second. If I use this kind of method, my program will slow down after a while.
Federico Piazza
@fivetech You can use
ping -c 1 www.google.com. It will stop after receiving the response. Btw, there are many useful commands for ping linux.die.net/man/8/ping. Ping cmd is the best command to check for connection.fivetech
Thank you so much. My app works fine. I set Thread.sleep(2000) and it doesn't use system resources much more now.
Federico Piazza
@fivetech glad to help. Any upvote will appreciated :)
fivetech
My reputation is not enough to vote up because I am new on this site
|
You could check to see if a common hostname (such as google) is resolvable through dns to an ip address.
Once that address has been resolved, you can check to see if it is reachable.
2 Comments
fivetech
Thanks for reply but isReachable method returns always false. I don't know how to manage this issue. :(
Brett Okken
The method basically does the same thing as ping, which many networks have blocked.