This discussion is archived
3 Replies Latest reply: Jan 22, 2013 2:01 AM by gimbal2 RSS

Check if network connection is avilable or not?

986310 Newbie
Currently Being Moderated
public static boolean isNetworkAvailable() {
try {
     Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

     while (interfaces.hasMoreElements()) {
     NetworkInterface interf = interfaces.nextElement();
          if (interf.isUp() && !interf.isLoopback())
          return true;
     }
               
} catch (SocketException e) {
     e.printStackTrace();
}
return false;
}



Code fails, if VM connections are available on the machine.

Edited by: 983307 on Jan 22, 2013 12:29 AM
  • 1. Re: Check if network connection is avilable or not?
    EJP Guru
    Currently Being Moderated
    Code fails if VM connections are available
    The code does exactly what it is supposed to do if there are VM connections available.

    More to the point, what exactly is the point? The best way to tell whether any resource is available is to try to use it, and handle the error or exceptions that result when it isn't. Trying to second-guess how the system decides that is futile and error-prone. If you want to use the network, just use it.
  • 2. Re: Check if network connection is avilable or not?
    986310 Newbie
    Currently Being Moderated
    I want some behaviour when network is unavailble.
    For that i had disconnected the network cable and used above code.
    But still it says that network is available by returning true value.

    And this isn't the case with all the machines.
    So i found that machines having multiple network adapters or having VM connection have this problem.

    So how to find this in code?
  • 3. Re: Check if network connection is avilable or not?
    gimbal2 Guru
    Currently Being Moderated
    983307 wrote:
    So how to find this in code?
    Like EJP described?

    a) try to actually make a connection
    b) if it fails, the network ain't working

    You can't make it any more dumb and simple than that.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points