import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; /** * @author zzl */ public class PortChecker { public static boolean isPortReachable(String host, int port, int timeout) { try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(host, port), timeout); return true; } catch (IOException e) { return false; } } public static void main(String[] args) { String host = "baidu.com"; // 要 ping 的远程服务器地址 int port = 80; // 要 ping 的端口号 int timeout = 2000; // 连接超时时间,单位毫秒 boolean isReachable = isPortReachable(host, port, timeout); if (isReachable) { System.out.println("Port " + port + " on " + host + " is alive!"); } else { System.out.println("Port " + port + " on " + host + " is dead!"); } } }
标签:java,socket,int,host,007,timeout,port From: https://www.cnblogs.com/fengzidexuanxue/p/18325914