我如何使用Java编程确定特定机器上端口的可用性?
也就是说,给定一个端口号,确定它是否已经被使用了吗?
我如何使用Java编程确定特定机器上端口的可用性?
也就是说,给定一个端口号,确定它是否已经被使用了吗?
这是来自Apache camel项目的implementation:
/**
* 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;
}
ServerSocket
,那么它应该这样做,并返回ServerSocket
。创建它,然后关闭它并返回它不能保证可以使用该端口创建下一个ServerSocket
。对于DatagramSocket
也是如此。 - user207421对于Java 7,您可以使用try-with-resource以获得更简洁的代码:
private static boolean available(int port) throws IllegalStateException {
try (Socket ignored = new Socket("localhost", port)) {
return false;
} catch (ConnectException e) {
return true;
} catch (IOException e) {
throw new IllegalStateException("Error while trying to check open port", e);
}
}
ConnectException: 'connection refused'
,是的,它应该返回 false。对于超时,它可能返回的任何内容都无效,因为实际答案是未知的。这就是为什么这种技术在这个目的上是无用的原因。 - user207421false
。相反,如果端口未被使用,则会引发异常,在这种情况下,您希望该方法返回true
。然而,正如JMax所评论的,这个测试很慢。 - hfontanez看起来从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)
会为你找到一个。
Socket(...)
的其他解决方案相比,它非常快速(在不到一秒钟的时间内测试1000个TCP端口)。public static boolean isTcpPortAvailable(int port) {
try (ServerSocket serverSocket = new ServerSocket()) {
// setReuseAddress(false) is required only on macOS,
// 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;
}
}
对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;
}
}
ServerSocket
和DatagramSocket
并返回后,某些内容可能会获取端口)。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;
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);
}
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");
}