cn.hutool.core.net.NetUtil#isUsableLocalPort(port)isUsableLocalPort(int port)
检测本地端口可用性
来自org.springframework.util.SocketUtils
上面方法如果不想引入jar:public static boolean isUsableLocalPort(int port) {
// issue#765@Github, 某些绑定非127.0.0.1的端口无法被检测到
try (ServerSocket ss = new ServerSocket(port)) {
ss.setReuseAddress(true);
} catch (IOException ignored) {
return false;
}
try (DatagramSocket ds = new DatagramSocket(port)) {
ds.setReuseAddress(true);
} catch (IOException ignored) {
return false;
}
return true;
}public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/C", "netstat -n -o | findstr :12345");
Process process = builder.start();
process.waitFor();
printProcessStreamAndKill(process.getInputStream());
}
private static void printProcessStream(InputStream inputStream) throws IOException {
int bytesRead = -1;
byte[] bytes = new byte[1024];
String output = "";
while ((bytesRead = inputStream.read(bytes)) > -1) {
output = output + new String(bytes, 0, bytesRead);
}
System.out.println(" The netstat command response is \r\n" + output);
}
public static void killProcess(String pid) throws Exception {
Runtime.getRuntime().exec(KILL + pid);
}
linux 同样的方式,命令为查找端口占用进程:lsof -i:12345
关闭进程:kill -9 ${pid}