套接字:使用Java发现端口可用性 [英] Sockets: Discover port availability using Java
本文介绍了套接字:使用Java发现端口可用性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Java以编程方式确定给定计算机中端口的可用性?
即给定端口号,确定它是否已被使用这是实现来自Apache 骆驼项目:
/ **
*检查特定端口是否可用。
*
* @param端口端口检查可用性
* /
public static boolean available(int port){
if(port< MIN_PORT_NUMBER || port> MAX_PORT_NUMBER){
抛出新的IllegalArgumentException(无效的起始端口:+端口);
}
ServerSocket ss = null;
DatagramSocket ds = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
ds = new DatagramSocket(port);
ds.setReuseAddress(true);
返回true;
} catch(IOException e){
} finally {
if(ds!= null){
ds.close();
}
if(ss!= null){
try {
ss.close();
} catch(IOException e){
/ *不应抛出* /
}
}
}
返回false;
}
他们正在检查DatagramSocket以检查UDP中的端口是否可用和TCP。
希望这会有所帮助。
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;
}
They are checking the DatagramSocket as well to check if the port is avaliable in UDP and TCP.
Hope this helps.
这篇关于套接字:使用Java发现端口可用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文