套接字:使用 Java 发现端口可用性 [英] Sockets: Discover port availability using Java
本文介绍了套接字:使用 Java 发现端口可用性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 Java 以编程方式确定给定机器中端口的可用性?
How do I programmatically determine the availability of a port in a given machine using Java?
即给定一个端口号,确定它是否已经被使用?
i.e given a port number, determine whether it is already being used or not?.
推荐答案
This is the implementation coming from the Apache camel project:
/**
* Checks to see if a specific port is available.
*
* @param port the port to check for availability
*/
public static boolean available(int port) {
if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
throw new IllegalArgumentException("Invalid start port: " + port);
}
ServerSocket ss = null;
DatagramSocket ds = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
ds = new DatagramSocket(port);
ds.setReuseAddress(true);
return true;
} catch (IOException e) {
} finally {
if (ds != null) {
ds.close();
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
/* should not be thrown */
}
}
}
return false;
}
他们也在检查 DatagramSocket 以检查端口是否在 UDP 和 TCP 中可用.
They are checking the DatagramSocket as well to check if the port is avaliable in UDP and TCP.
希望这会有所帮助.
这篇关于套接字:使用 Java 发现端口可用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文