用Java检测远程主机是否能被连接

有人推荐使用java的Runtime.exec()方法来直接调用系统的Ping命令。也有人完成了纯Java实现Ping的程序,使用的是Java的NIO包(native io, 高效IO包)。
我个人认为,没有必要用Java再重新写一个Ping命令,因为没有多大意义。更多的人是关心用Java实现ping在应用程序中来测试一个远程主机是否可用。其实自从Java 1.5,java.net包中就实现了ICMP ping的功能。以下我来介绍:
自java 1.5以后,java.net.InetAddress中一个方法:Java代码public boolean isReachable(int timeout) throws IOException
public boolean isReachable(int timeout) throws IOException 它实现了ICMP ECHO REQUEST。
package seleniumapi;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Demo {

    public static void main(String[] args) throws Exception, IOException {
        // TODO Auto-generated method stub
        String host = "192.168.1.181";
        int timeOut = 3000; //超时应该在3钞以上
        boolean status = InetAddress.getByName(host).isReachable(timeOut);
        System.out.println(status);
    }

}
原文地址:https://www.cnblogs.com/longronglang/p/6937429.html