How to check your internet connection in Java

I am working on a Java project that must have an Internet connection at all times.

I want my program to continue checking the Internet connection at certain intervals (say, 5 or 10 seconds) and display a message as soon as an Internet connection is not found.

I tried using the isReachable method to achieve this function, below is the code -

try { InetAddress add = InetAddress.getByName("www.google.com"); if(add.isReachable(3000)) System.out.println("Yes"); else System.out.println("No"); } catch (UnknownHostException e) { System.out.println("unkownhostexception"); } catch (IOException e) { System.out.println("IoException"); } 

But this code always returns "No". What is the problem with this code?

thanks

+6
source share
2 answers

The only way I know is to send the package to some well-known host, known in the sense that you know that it will always work and start from the calling site.

However, for example, if you select a named host, ping may fail due to a DNS lookup failure.

I think you should not worry about this problem: if your program needs an Internet connection, it sends or receives data. Communication is not a continuous concept, like a river, but rather a road. So just use the Java standard to handle connection errors: IOExceptiions. When your program needs to send data, the core API will issue an IOE in case the network is down. If your program is expecting data, instead use a timeout or something similar to detect possible errors in the network stack and report this to the user.

+9
source

I agree with Raffael’s suggestion if you just need to use the Internet often. Just try to do this and be prepared to handle exceptions when it doesn't work.

If for some reason you need to monitor the availability of the Internet, even if you are not going to use it yet and do not know who you will connect with, just try connecting to a well-known site (google.com, amazon.com, baidu.com. ..).

This will work to test several sites:

 public static void main(String[] args) { System.out.println( "Online: " + (testInet("myownsite.example.com") || testInet("google.com") || testInet("amazon.com")) ); } public static boolean testInet(String site) { Socket sock = new Socket(); InetSocketAddress addr = new InetSocketAddress(site,80); try { sock.connect(addr,3000); return true; } catch (IOException e) { return false; } finally { try {sock.close();} catch (IOException e) {} } } 
+15
source

Source: https://habr.com/ru/post/946884/


All Articles