Question

How can I figure out network connection is available in java? I want to get information about network connection. If it is available, I'll connect to network for fetching data otherwise I use local database.

Is There any solution?

Was it helpful?

Solution 2

Such as @igor said: "Try to connect the network, as you said. If fails, repeat e.g. 3 times. If still failling, use local database. You don't have to additionally ping anything."

For Example:

    public class InternetConnection {
    /*  use at least one reliable host, in most cases you will want
        to use the one you're working with later    */
    private static final String CHECK_URL = "http://www.t-online.de/";
    public static InternetConnectionState isAvailable() {
        try {
            URL url = new URL(InternetConnection.CHECK_URL);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            Object objData = urlConnection.getContent();
        } catch(UnknownHostException exception) {
            return new InternetConnectionState(false);
        } catch(IOException exception) {
            return new InternetConnectionState(false);
        }
        return new InternetConnectionState(true);
    }
}

Main link

OTHER TIPS

Try to connect the network, as you said. If fails, repeat e.g. 3 times. If still failling, use local database. You don't have to additionally ping anything.

For simplicity you can use Jodd HTTP library, for example:

try {
    HttpRequest.get("http://stackoverflow.com").send();
    return true;
} catch (Exception ex) {
    return false;
}

You can ping the host. See

java code to ping an IP address

If you want to check whether database is accessible or not you may catch the Connection Exceptions which can occur during the attempt to connect. Subsequently you can use local database if it fails

You can use java.net.NetworkInterface for that, here's a simple example no how to do it:

public boolean isConnectedToNetwork() {
    Enumeration<NetworkInterface> interfaceEnumeration = NetworkInterface.getNetworkInterfaces();
    while (interfaceEnumeration.hasMoreElements()) {
    NetworkInterface each = interfaceEnumeration.nextElement();

     if (!each.isLoopback() && each.isUp()) {
          return true;
      }
    }
    return false;
} 

Notice that you have to check if it's not a loopback interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top