2008年7月2日 星期三

How to detect the network device's status

Recently, I revised my RFID controller application which developed early.
The RFID readers we used is IP based whcih means the controller program has to deal with the network status. If the network down or the RFID reader halt, the controller program have to take some actions to reflect the situation and let the RFID reader back to work ASAP.

The most easy way to know the network status of a target device is using ICAMP to get the ACK from the target machine. However, JDK doesn't provide too many support on this.

I found there are many post already discuss on this topic. I have try several methods list in Reference section. The most easily solution is using Runtime.getRuntime().exec("ping " + host); . Althrough this method is only work on Windows but it just fulfill my needs and very stable. I also tried the method InetAddress.isReachable(timeout), but I am not satisfied on the result. I found sometimes the target is to busy to response the InetAddress.isReachable(timeout) will report the target is not reachable.
Hence, the first solution was taken. I list part of the code in my watch dog program.
public static boolean ping( String ipstr )
{
boolean retv=false;
try {
InputStream ins = Runtime.getRuntime()
.exec("ping -n 1 -w 2000 "+ipstr ).getInputStream();

Thread.sleep(5000);
byte[] prsbuf = new byte[ins.available()];
ins.read( prsbuf );
String parsstr = new StringTokenizer( new
String( prsbuf ), "%" ).nextToken().trim();

System.out.println(parsstr);
if( !parsstr.endsWith( "100" ) ) retv=true;
}
catch( Exception e )
{
retv=false;
}
return retv;
}
Most of the code came from the internet, but I forget the source. I am really appreciate the code. Thanks.

Reference:

  1. http://java.chinaitlab.com/base/749168.html
  2. http://www.rgagnon.com/javadetails/java-0093.html

沒有留言: