From 67244e2b010a4c5785d94ed0c4c075a03d2bbc14 Mon Sep 17 00:00:00 2001 From: 1091234881 <49577269+1091234881@users.noreply.github.com> Date: Wed, 20 Apr 2022 14:10:11 +0800 Subject: [PATCH] Update NetUtils.java MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 无法检测本地端口时候被占用 创建 ServerSocket 时 指定本地ip 端口被占用 异常为 java.net.BindException: Address already in use (Bind failed) --- util/src/main/java/com/zfoo/util/net/NetUtils.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/util/src/main/java/com/zfoo/util/net/NetUtils.java b/util/src/main/java/com/zfoo/util/net/NetUtils.java index 4dd9da09..52bb3943 100644 --- a/util/src/main/java/com/zfoo/util/net/NetUtils.java +++ b/util/src/main/java/com/zfoo/util/net/NetUtils.java @@ -114,9 +114,12 @@ public class NetUtils { // 给定的IP未在指定端口范围中 return false; } - try (ServerSocket ss = new ServerSocket(port)) { + try { + InetAddress localHost = InetAddress.getLocalHost(); + ServerSocket ss = new ServerSocket(port, 50, localHost); + ss.close(); return true; - } catch (IOException e) { + } catch (Exception e) { return false; } }