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

相关内容

    暂无相关文章