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
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值