From efdb99f8cecc4afb592afad79c761081d5d5cf22 Mon Sep 17 00:00:00 2001 From: lee <4766465@qq.com> Date: Wed, 18 Dec 2024 13:27:00 +0800 Subject: [PATCH] init --- xxl-job/xxl-job-core/src/main/java/com/xxl/job/core/util/NetUtil.java | 70 +++++++++++++++++++++++++++++++++++ 1 files changed, 70 insertions(+), 0 deletions(-) diff --git a/xxl-job/xxl-job-core/src/main/java/com/xxl/job/core/util/NetUtil.java b/xxl-job/xxl-job-core/src/main/java/com/xxl/job/core/util/NetUtil.java new file mode 100644 index 0000000..41d285f --- /dev/null +++ b/xxl-job/xxl-job-core/src/main/java/com/xxl/job/core/util/NetUtil.java @@ -0,0 +1,70 @@ +package com.xxl.job.core.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.ServerSocket; + +/** + * net util + * + * @author xuxueli 2017-11-29 17:00:25 + */ +public class NetUtil { + private static Logger logger = LoggerFactory.getLogger(NetUtil.class); + + /** + * find avaliable port + * + * @param defaultPort + * @return + */ + public static int findAvailablePort(int defaultPort) { + int portTmp = defaultPort; + while (portTmp < 65535) { + if (!isPortUsed(portTmp)) { + return portTmp; + } else { + portTmp++; + } + } + portTmp = defaultPort--; + while (portTmp > 0) { + if (!isPortUsed(portTmp)) { + return portTmp; + } else { + portTmp--; + } + } + throw new RuntimeException("no available port."); + } + + /** + * check port used + * + * @param port + * @return + */ + public static boolean isPortUsed(int port) { + boolean used = false; + ServerSocket serverSocket = null; + try { + serverSocket = new ServerSocket(port); + used = false; + } catch (IOException e) { + logger.info(">>>>>>>>>>> xxl-job, port[{}] is in use.", port); + used = true; + } finally { + if (serverSocket != null) { + try { + serverSocket.close(); + } catch (IOException e) { + logger.info(""); + } + } + } + return used; + } + +} -- Gitblit v1.9.3