0

I have a small project which needs internet connection. Unfortunately my internet is occasionally down. Then it throws away exception:

"java.net.SocketException: Network is unreachable"

...

My idea was to check internet connection before I do any operation and if it's down, just wait a few seconds and try again and again until its not working. But it throws same exception.

My code:

        URL url = new URL("https://www.google.com");
        URLConnection conn = url.openConnection();


        InetAddress check = InetAddress.getByName("www.google.com");

        while (check.isReachable(3000)) {
            wait(5000);
        }

1 Answers1

0

This might be what you're looking for. If an exception is thrown or isReachable is false the loop will keep checking but as soon as it is isReachable is true the loop will exit.

    URL url = new URL("https://www.google.com");
    URLConnection conn = url.openConnection();

    InetAddress check = InetAddress.getByName("www.google.com");

        while (true) {
            try {
                boolean isReachable = check.isReachable(3000);
                if (isReachable) {
                    break;
                }
            } catch (Exception e) {
                wait(5000);
            }
        }
crabe
  • 322
  • 4
  • 15
  • It looks great and I understand how it should works. But it doesn't. When the connection is reachable, the loop is still repeating. It doesn't jump out of it... :( Why? – NaughtyMike Feb 04 '15 at 20:15
  • The method seems to be unreliable see this post: http://stackoverflow.com/questions/9922543/why-does-inetaddress-isreachable-return-false-when-i-can-ping-the-ip-address – crabe Feb 05 '15 at 08:34