设为首页 加入收藏

TOP

Java 获取可用 UDP 端口号的方法
2014-11-24 07:40:26 来源: 作者: 【 】 浏览:1
Tags: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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇探讨Linux kernel中对序列号超前.. 下一篇C++ sort()函数简单用法

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Libevent C++ 高并发 (2025-12-26 00:49:30)
·C++ dll 设计接口时 (2025-12-26 00:49:28)
·透彻理解 C 语言指针 (2025-12-26 00:22:52)
·C语言指针详解 (经典 (2025-12-26 00:22:49)
·C 指针 | 菜鸟教程 (2025-12-26 00:22:46)