3

I have a java application which runs every 10 minutes. So whenever the thread starts executing i have to check whether there is internet connectivity or not. So i was using the Socket class for this. But the problem here is the socket class works fine if the wire is not connected to my system. For me if i plug in the wire then i have LAN but no internet. In this case the socket class fails to throw an error. Here is my code -

Socket socket = null;
     try {
         socket = new Socket("www.google.com", 80);
     } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {            
         if (socket != null) try { socket.close();

       } 
       catch(IOException e) {
           e.printStackTrace();
        }
      System.exit(0);
     }

I checked out the code here - Detect internet Connection using Java. But using the getContent() does not help.

Community
  • 1
  • 1
Dan
  • 801
  • 2
  • 14
  • 29
  • Not related to your problem but you should know that `finally` section wont be executed if catch will invoke `System.exit(0)` (at least in Java7). – Pshemo Aug 17 '13 at 18:49

3 Answers3

1

Have you tried?

boolean hasInternetAccess  = InetAddress.getByName("www.google.com").isReachable();
Skylion
  • 2,696
  • 26
  • 50
1

You should just try to connect to whatever it is you need to connect to, and handle the failure as it occurs. There is no magical predictor of success.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

Two answers. 1. The code behind the link is good. You basically need to receive data from an URL to be sure it is really reachable. I would additionally configure the connection with setUseCaches(false) 2. Your up front check does not help you. You can still loose connection half way down your program. So, just let your code run. When it detects a connection problem print out the error to the user an end gracefully.

jboi
  • 11,324
  • 4
  • 36
  • 43