代理配置-端口映射,配置服务端端口时,检查端口是否被占用

This commit is contained in:
Metal
2023-07-17 21:06:51 +08:00
parent abab45785b
commit a7b2694204
5 changed files with 79 additions and 9 deletions
@@ -133,4 +133,12 @@ public class PortPoolController {
portPoolService.deleteBatch(req.getIds());
}
@Get
@Mapping("/port-available")
public boolean portAvailable(Integer port) {
ParamCheckUtil.checkNotNull(port, "port");
return portPoolService.portAvailable(port);
}
}
@@ -28,6 +28,7 @@ import org.apache.ibatis.solon.annotation.Db;
import org.dromara.neutrinoproxy.server.controller.req.system.*;
import org.dromara.neutrinoproxy.server.controller.res.system.*;
import org.dromara.neutrinoproxy.server.dal.entity.PortGroupDO;
import org.dromara.neutrinoproxy.server.util.PortAvailableUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
@@ -198,4 +199,13 @@ public class PortPoolService {
visitorChannelService.updateVisitorChannelByPortPool(portPoolDO.getPort(), EnableStatusEnum.DISABLE.getStatus());
});
}
/**
* 检查端口是否被占用
* @param port
* @return
*/
public boolean portAvailable(Integer port) {
return PortAvailableUtil.isPortAvailable(port);
}
}
@@ -0,0 +1,39 @@
package org.dromara.neutrinoproxy.server.util;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* 检查端口是否被占用
* 文章参考:https://blog.csdn.net/xingluxiaoseng/article/details/40148527
*/
public class PortAvailableUtil {
private static void bindPort(String host, int port) throws IOException {
Socket s = new Socket();
s.bind(new InetSocketAddress(host, port));
s.close();
}
/**
* 端口占用判断,若是端口被占用,则会抛出IOException异常,表示端口被占用
* @param port
* @return
*/
public static boolean isPortAvailable(int port) {
try {
bindPort("0.0.0.0", port);
bindPort(InetAddress.getLocalHost().getHostAddress(), port);
return true;
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
System.out.println("端口被占用:"+isPortAvailable(9527));
}
}