判断TCP端口是否可以正常打开,检测TCP/或基于TCP的服务器运行情况
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class TCPConnectionTester {
private static final int CONNECT_TIMEOUT_MS = 3000;
/**
* 测试TCP连接
* @param ip IP地址
* @param port 端口号
* @return 如果连接成功,返回true;否则返回false
*/
public static boolean testTCPConnection(String ip, int port) {
return testTCPConnection(ip, port, CONNECT_TIMEOUT_MS);
}
/**
* 测试TCP连接(可自定义超时时间)
* @param ip IP地址
* @param port 端口号
* @param timeoutMs 超时时间(毫秒)
* @return 如果连接成功,返回true;否则返回false
*/
public static boolean testTCPConnection(String ip, int port, int timeoutMs) {
if (ip == null || ip.trim().isEmpty()) {
throw new IllegalArgumentException("IP地址不能为空");
}
if (port < 1 || port > 65535) {
throw new IllegalArgumentException("端口号必须在1-65535范围内");
}
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(ip, port), timeoutMs);
return true;
} catch (SocketTimeoutException e) {
System.err.println("连接超时: " + ip + ":" + port);
} catch (IOException e) {
System.err.println("连接失败 " + ip + ":" + port + ": " + e.getMessage());
}
return false;
}
/**
* 带详细信息的测试方法
*/
public static ConnectionResult testWithDetails(String ip, int port) {
long startTime = System.currentTimeMillis();
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(ip, port), CONNECT_TIMEOUT_MS);
long duration = System.currentTimeMillis() - startTime;
return new ConnectionResult(true, duration, "连接成功");
} catch (SocketTimeoutException e) {
long duration = System.currentTimeMillis() - startTime;
return new ConnectionResult(false, duration, "连接超时");
} catch (IOException e) {
long duration = System.currentTimeMillis() - startTime;
return new ConnectionResult(false, duration, "连接失败: " + e.getMessage());
}
}
// 内部结果类
public static class ConnectionResult {
private final boolean success;
private final long durationMs;
private final String message;
public ConnectionResult(boolean success, long durationMs, String message) {
this.success = success;
this.durationMs = durationMs;
this.message = message;
}
// getters...
public boolean isSuccess() { return success; }
public long getDurationMs() { return durationMs; }
public String getMessage() { return message; }
@Override
public String toString() {
return String.format("连接%s - 耗时: %dms - %s",
success ? "成功" : "失败", durationMs, message);
}
}
}
支持 Ctrl+A 全选,Ctrl+C 复制