007-java使用socket测试远程服务器的某个端口是否可连接
import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; /** * @author zzl
* ai生成,仅做记录 */ 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!"); } } }