Reputation: 361
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 ?
Upvotes: 1
Views: 303
Reputation: 6306
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.
Upvotes: 0
Reputation: 31035
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
Upvotes: 2