简体   繁体   中英

How to check if the computer is connected to the internet?

I have seen that this question had been asked before in SO. Some of the threads are:

All these threads are pretty old. The approaches that are defined there are:

  • Opening an HttpURLConnection by openConnection() .
  • Checking InetAddress.isReachable .
  • Executing ping command through Process and processing the output.

I have seen if I use the second approach to check the connectivity with www.google.com then it is returning false, which should not be the result. But the first way works. I cannot use the last way since the respondent himself said it.

I have also seen the following way:

private boolean isConnected(Socket socket, String address) {
    if(socket == null) {
        throw new NullPointerException("Socket cannot be null");            
    }

    try {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(address, 80);
        socket.connect(inetSocketAddress);
        return true;
    } catch (Throwable cause) {
        LOGGER.error(cause.getMessage(), cause);
        return false;
    }
}

By this way I am getting right output. The aforementioned threads mentioned that there is no proper way to validate if the computer is connected to the internet or not. But since these threads are old so I am hoping there might be some new way out there by which I can achieve what I want. Also I have to consider that there are various ways to access internet like LAN, Broadband, Dial Up, DSL etc and some server might block ping access or can block some IP.

Any pointer would be very helpful.

You could use the NetworkInterface class, it has a isUp() method which returns boolean indicating whether the particular interface is up and running (which could indicate if it's used for internet connection).

API: http://docs.oracle.com/javase/7/docs/api/java/net/NetworkInterface.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM