1. 程式人生 > >java實現ping的功能

java實現ping的功能

使用InetAddress的isReachable方法。
import java.net.InetAddress;
public class MainTest {
 public static void main(String[] args) {
  try {
   int timeOut = 3000;
   byte[] ip = new byte[] { (byte) 192, (byte) 168, (byte) 100, (byte) 151 };
   int retry = 4;
   InetAddress address = InetAddress.getByAddress(ip);
   for (int i = 0; i < retry; i++) {
    if (address.isReachable(timeOut)) {
     System.out.println(i + " OK");
    } else {
     System.out.println(i + " LOSS");
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}