Java 获取可用 UDP 端口号的方法

                        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

原文链接: http://stackoverflow.com/questions/2675362/how-to-find-an-available-port。           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/hgguhff/article/details/87805433