Answers:
/**
* 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中是否可用。
希望这可以帮助。
ServerSocket
对某个端口的侦听,则应这样做,然后返回ServerSocket
。创建它,然后关闭它并返回它提供了零保证,即ServerSocket
可以使用该端口创建后续项。同上DatagramSocket
。
对于Java 7,您可以使用try-with-resource获得更紧凑的代码:
private static boolean available(int port) {
try (Socket ignored = new Socket("localhost", port)) {
return false;
} catch (IOException ignored) {
return true;
}
}
ConnectException: 'connection refused'
,是,它应该返回false。对于超时,它无法返回的任何内容都是有效的,因为实际答案未知。这就是为什么这种技术对这个目的没有用的原因。
从Java 7开始,David Santamaria的答案似乎不再可靠。但是,看起来您仍然可以可靠地使用Socket来测试连接。
private static boolean available(int port) {
System.out.println("--------------Testing port " + port);
Socket s = null;
try {
s = new Socket("localhost", port);
// If the code makes it this far without an exception it means
// something is using the port and has responded.
System.out.println("--------------Port " + port + " is not available");
return false;
} catch (IOException e) {
System.out.println("--------------Port " + port + " is available");
return true;
} finally {
if( s != null){
try {
s.close();
} catch (IOException e) {
throw new RuntimeException("You should handle this error." , e);
}
}
}
}
如果您不太关心性能,则可以始终尝试使用ServerSocket类在端口上进行侦听。如果抛出异常,则使用它。
public static boolean isAvailable(int portNr) {
boolean portFree;
try (var ignored = new ServerSocket(portNr)) {
portFree = true;
} catch (IOException e) {
portFree = false;
}
return portFree;
}
编辑:如果您想要做的就是选择一个空闲端口,那么new ServerSocket(0)
它将为您找到一个。
以下解决方案受Spring-core(Apache许可)的SocketUtils实现的启发。
与使用Socket(...)
它的其他解决方案相比,速度非常快(不到一秒钟即可测试1000个TCP端口):
public static boolean isTcpPortAvailable(int port) {
try (ServerSocket serverSocket = new ServerSocket()) {
// setReuseAddress(false) is required only on OSX,
// otherwise the code will not work correctly on that platform
serverSocket.setReuseAddress(false);
serverSocket.bind(new InetSocketAddress(InetAddress.getByName("localhost"), port), 1);
return true;
} catch (Exception ex) {
return false;
}
}
基于try / catch套接字的解决方案可能无法产生准确的结果(套接字地址为“ localhost”,并且在某些情况下,端口可能会被“回送”接口“占用”,至少在Windows上,我已经看到该测试失败,即prot被错误地声明为可用)。
有一个很酷的库,名为SIGAR,以下代码可以帮助您:
Sigar sigar = new Sigar();
int flags = NetFlags.CONN_TCP | NetFlags.CONN_SERVER | NetFlags.CONN_CLIENT; NetConnection[] netConnectionList = sigar.getNetConnectionList(flags);
for (NetConnection netConnection : netConnectionList) {
if ( netConnection.getLocalPort() == port )
return false;
}
return true;
David Santamaria指出的答案的清理:
/**
* Check to see if a port is available.
*
* @param port
* the port to check for availability.
*/
public static boolean isPortAvailable(int port) {
try (var ss = new ServerSocket(port); var ds = new DatagramSocket(port)) {
return true;
} catch (IOException e) {
return false;
}
}
这仍然是受user207421在评论大卫·圣玛丽亚的回答中指出的竞争条件(东西可以抓住港口此方法关闭后ServerSocket
并DatagramSocket
返回)。
就我而言,它有助于尝试并连接到端口-如果服务已经存在,它将响应。
try {
log.debug("{}: Checking if port open by trying to connect as a client", portNumber);
Socket sock = new Socket("localhost", portNumber);
sock.close();
log.debug("{}: Someone responding on port - seems not open", portNumber);
return false;
} catch (Exception e) {
if (e.getMessage().contains("refused")) {
return true;
}
log.error("Troubles checking if port is open", e);
throw new RuntimeException(e);
}
就我而言,我必须使用DatagramSocket类。
boolean isPortOccupied(int port) {
DatagramSocket sock = null;
try {
sock = new DatagramSocket(port);
sock.close();
return false;
} catch (BindException ignored) {
return true;
} catch (SocketException ex) {
System.out.println(ex);
return true;
}
}
别忘了先导入
import java.net.DatagramSocket;
import java.net.BindException;
import java.net.SocketException;
我已经试过像这样的东西,对我来说真的很好
Socket Skt;
String host = "localhost";
int i = 8983; // port no.
try {
System.out.println("Looking for "+ i);
Skt = new Socket(host, i);
System.out.println("There is a Server on port "
+ i + " of " + host);
}
catch (UnknownHostException e) {
System.out.println("Exception occured"+ e);
}
catch (IOException e) {
System.out.println("port is not used");
}