套接字:使用Java发现端口可用性如何使用Java以编程方式确定给定计算机中端口的可用性?即给定一个端口号,确定它是否已被使用?
3 回答
MYYA
TA贡献1868条经验 获得超4个赞
/** * Checks to see if a specific port is available. * * @param port the port to check for availability */public static boolean available(int port) { if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) { throw new IllegalArgumentException("Invalid start port: " + port); } ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); ds = new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch (IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { /* should not be thrown */ } } } return false;}
他们还检查DatagramSocket以检查端口是否可用于UDP和TCP。
希望这可以帮助。
汪汪一只猫
TA贡献1898条经验 获得超8个赞
对于Java 7,您可以使用try-with-resource来获得更紧凑的代码:
private static boolean available(int port) { try (Socket ignored = new Socket("localhost", port)) { return false; } catch (IOException ignored) { return true; }}
蝴蝶不菲
TA贡献1810条经验 获得超4个赞
从Java 7开始,David Santamaria的答案似乎不再可靠。但是,看起来您仍然可以可靠地使用Socket来测试连接。
private static boolean available(int port) { System.out.println("--------------Testing port " + port); Socket s = null; try { s = new Socket("localhost", port); // If the code makes it this far without an exception it means // something is using the port and has responded. System.out.println("--------------Port " + port + " is not available"); return false; } catch (IOException e) { System.out.println("--------------Port " + port + " is available"); return true; } finally { if( s != null){ try { s.close(); } catch (IOException e) { throw new RuntimeException("You should handle this error." , e); } } }}
添加回答
举报
0/150
提交
取消