I have seen that this question had been asked before in SO. Some of the threads are:
- How to check if internet connection is present in java.
- Detect internet Connection using Java.
- Why does InetAddress.isReachable return false, when I can ping the IP address?.
All these threads are pretty old. The approaches that are defined there are:
- Opening an
HttpURLConnection
byopenConnection()
. - Checking
InetAddress.isReachable
. - Executing
ping
command throughProcess
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.