How to detect network breakage using java program?
Is there any way to detect the network breakage or weaker network, using Jav开发者_开发技巧a?
you can intermittently test a http connection to a known host such as google and detect ConnectionExceptions
URLConnection con = new URL("http://www.google.com/").openConnection();
con.setUseCaches(false);
con.setAllowUserInteraction(false);
while(true)
{
try
{
con.connect();
con.getContentType(); // just to make sure the connection works
// sleep for some interval
}
catch(IOException e)
{
// handle and break
}
}
In general, it is not possible to detect and diagnose network "breakage" with 100% accuracy in Java or in any other language. Indeed, is not even clear what constitutes "breakage". This is why (for example) your favourite web browser gives you a vague error message when you enter an bogus DNS name or IP address in a URL.
The problem is that there are many situations where it is not possible to know what caused a network interaction to fail:
- is my machine unplugged?
- is something jabbering on my local network?
- has my ISP's network gone down due to a power failure?
- is an internet routing instability causing my packets to get routed to Turkmanistan?
- is Google down ... or being DoSed by some Russian hacking mob?
Many of these situations are hard to diagnose. And trying to diagnose things from Java is harder, because Java does not offer standard APIs for doing such things as sending ICMP packets. Basically, you are restricted to trying to interpret the Java exceptions that you get back when an attempt to connect a socket fails.
IMO, your best bet is to make use of existing command line tools such as 'ping' and 'traceroute', and learn to read tea leaves. Or if that is too hard, leave network diagnosis to the experts.
精彩评论