Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test the availability of the internet in Java?

Tags:

java

I don't want to tell the hard way that the internet is unavailable when I catch an exception from url.openStream().

Is there a simple way to tell if the computer is connected to the internet in Java? In this scenario, "connected to the internet" means being able to download data from a specific url.

If I try to download from it and it is not available, then the program hangs for a bit. I dont want that hanging. Therefore, i need a fast way of querying whether the website is available or not.

like image 625
Penchant Avatar asked Mar 13 '09 22:03

Penchant


2 Answers

The problem you are trying to avoid is waiting for for your http connection to determine that the URL you are trying to access is really unavailable. In order to achieve this you need to stop using url.openStream() which is a shortcut for openConnection().getInputStream() and get some finer control over your connection.

URLConnection conn = url.openConnection();  
conn.setConnectTimeout(timeoutMs);  
conn.setReadTimeout(timeoutMs);  
in = conn.getInputStream();  

This code will allow you to timeout the connection attempt if either the connection or the read exceeds the time you provide in the timeoutMs paramater.

like image 196
Steve Weet Avatar answered Sep 22 '22 01:09

Steve Weet


Use

Process p1 = java.lang.Runtime.getRuntime().exec("ping www.google.com");
System.out.println(p1.waitFor());
// return code for p1 will be 0 if internet is connected, else it will be 1
like image 37
Naga Rishi Avatar answered Sep 20 '22 01:09

Naga Rishi