Reputation: 35
public boolean isReachable(String ipAddress, int port, int timeout)
{
Socket socket = new Socket();
Exception exception = null;
try {
socket.connect(new InetSocketAddress(ipAddress, port), timeout);
}
catch (IOException e) { exception = e; }
finally {
try { socket.close(); } catch (Exception e) {e.printStackTrace(); }
}
return exception == null;
}
this code works when i am connected to the internet. but it also works when i am disconnected from ISP side.(like when adsl service date is expired or the traffic is finished). please tell me where the problem is?
Upvotes: 0
Views: 2602
Reputation: 319
Traffic blocking strategies vary from ISP to ISP. The only surefire method to check if the site is really available, is to try to get the actual response stream and analyze it.
The obvious way for HTTP server would be, use URLConnection, send a GET / request, check if the response code is 200 OK. But there's no universal way of checking ANY kind of server - you need to know what does the usual response look like.
Upvotes: 1
Reputation: 5072
You should go for InetAddress that has the isReachable() method, that by the docs should:
public boolean isReachable(int timeout) throws IOException
Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.
Upvotes: 0