Java 获取可用 UDP 端口号的技巧
发布时间:2021-11-21 19:27:35 所属栏目:教程 来源:互联网
导读:Java 获取可用 UDP 端口号的方法。TCP 获取的办法类似于这个。 方法一:如果你不介意获取的端口号范围,可以使用 DatagramSocket 的构造方法定义 0 为其端口号,系统将为其分配一个闲置的端口号: public static DatagramSocket getRandomPort() throws Sock
Java 获取可用 UDP 端口号的方法。TCP 获取的办法类似于这个。 方法一:如果你不介意获取的端口号范围,可以使用 DatagramSocket 的构造方法定义 0 为其端口号,系统将为其分配一个闲置的端口号: public static DatagramSocket getRandomPort() throws SocketException { DatagramSocket s = new DatagramSocket(0); return s; } 方法二:如果你想使用一套特定范围的端口号,最简单的办法就是依次遍历这些端口号直到有一个可用: public static DatagramSocket getRangePort(int[] ports) throws IOException { for (int port : ports) { try { return new DatagramSocket(port); } catch (IOException ex) { continue; // try next port } } // if the program gets here, no port in the range was found throw new IOException("no free port found"); } 测试代码: import java.io.IOException; import java.net.DatagramSocket; import java.net.SocketException; public class UdpPortTest { public static void main(String[] args) throws IOException { DatagramSocket socket = getRandomPort(); System.out.println("__________socket.getLocalPort():" + socket.getLocalPort()); DatagramSocket socket2 = getRangePort(new int[] { 3843, 4584, 4843 }); System.out.println("__________socket2.getLocalPort():" + socket2.getLocalPort()); } public static DatagramSocket getRandomPort() throws SocketException { DatagramSocket s = new DatagramSocket(0); return s; } public static DatagramSocket getRangePort(int[] ports) throws IOException { for (int port : ports) { try { return new DatagramSocket(port); } catch (IOException ex) { continue; // try next port } } // if the program gets here, no port in the range was found throw new IOException("no free port found"); } } 打印结果: __________socket.getLocalPort():2156 __________socket2.getLocalPort():3843 ![]() (编辑:PHP编程网 - 黄冈站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |