在我们的应用程序中,我们需要检查某些主机的某些端口是否可用于通信。在此检查阶段,我们不进行真正的沟通 - 我们只需检查端口是否打开。由于必须立即检查许多端口,我们最初使用的是NIO方法(Selector + SocketChannel类):
package test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class TestNIO {
public static void main(final String... params) {
final List<String> portsToCheck = Arrays.asList(new String[] {"443", "5989"});
final List<String> openPorts = new ArrayList<String>();
final String host = "<SOME_IP>";
final int timeout = 5000;
Selector selector = null;
if (!portsToCheck.isEmpty()) {
try {
selector = Selector.open();
for (final String port : portsToCheck) {
final SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress(host, Integer.valueOf(port)));
channel.register(selector, SelectionKey.OP_CONNECT);
}
final int readyChannels = selector.select(timeout);
if (readyChannels != 0) {
final Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
final SelectionKey selKey = it.next();
try {
if (selKey.isValid() && selKey.isConnectable()) {
final SocketChannel channel = (SocketChannel) selKey.channel();
try {
if (channel.finishConnect()) {
openPorts.add(String.valueOf(channel.socket().getPort()));
}
} catch (final IOException ex) {
ex.printStackTrace();
} finally {
channel.close();
}
}
} catch (final Exception ex) {
ex.printStackTrace();
} finally {
selKey.cancel();
}
it.remove();
}
}
} catch (final IOException ex) {
ex.printStackTrace();
} finally {
try {
if (selector != null && selector.isOpen()) {
selector.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.print("Open ports: " + openPorts.toString());
}
}
}
}
这种方法多年来成功运作,让我们说数百名客户,直到我们的客户之一,这种方法导致了问题。也就是说,从客户端(运行此检查,它是Windows Server 2012 R2)到只有一个SSL端口的服务器(它的ESXi)的连接保持建立状态,并且在重新启动服务器之前永远不会关闭。这只发生在一个SSL端口(标准443),例如另一个SSL端口 - 5989(它的HTTPS CIM服务器),这不会发生。看起来这是因为Windows端的一些配置:1。只发生几个HTTPS端口之一; 2.适用于连接到此Windows客户端的任何ESXi服务器; 3.连接到相同ESXi服务器的其他Windows客户端不会发生此问题。问题是客户不希望与我们合作找到根本原因,我们必须自己猜测。我们使用另一种经典方法来检查SSL端口,即使在这个有问题的系统中也能正常工作。这是:
package test;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class TestHttpUrlConnection {
public static void main(final String... params) {
final List<String> portsToCheck = Arrays.asList(new String[] {"443", "5989"});
final List<String> openPorts = new ArrayList<String>();
final String host = "<SOME_IP>";
final int timeout = 5000;
if (!portsToCheck.isEmpty()) {
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
});
for (final String port : portsToCheck) {
HttpsURLConnection connection = null;
OutputStreamWriter out = null;
try {
connection = (HttpsURLConnection) new URL(
"https://" + host + ":" + Integer.valueOf(port)).openConnection();
connection.setDoOutput(true);
connection.setConnectTimeout(timeout);
final OutputStream os = connection.getOutputStream();
out = new OutputStreamWriter(os, "UTF8");
out.close();
openPorts.add(port);
} catch(final IOException ex) {
ex.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (final IOException ex) {
ex.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
}
System.out.print("Open ports: " + openPorts.toString());
}
}
private static void trustAllHttpsCertificates() {
try {
final TrustManager[] trustAllCerts = new TrustManager[1];
trustAllCerts[0] = new TrustAllManager();
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private static class TrustAllManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(final X509Certificate[] certs, final String authType) throws CertificateException {
// Empty
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
// Empty
}
}
}
但是客户希望我们告诉他为什么一种方法有效而另一种无效的原因。有人可以帮忙吗?
更新
我发现在有问题的系统上,即使遵循代码也会导致每个连接保持ESTABLISHED并且不会释放回系统的情况。调用套接字时,这不是NIO和显式close()
:
Socket sock = new Socket();
SocketAddress serverSocketAddress = new InetSocketAddress(host, port);
try {
sock.connect(serverSocketAddress, timeout);
if (sock.isConnected()) {
openPorts.add(port);
}
} catch (IOException e) {
ex.printStackTrace();
} finally {
if (sock != null) {
try {
sock.close();
} catch (IOException e) {
ex.printStackTrace();
}
}
}
将keepAlive
设置为false
并不会改变这种情况。
更新2
在非SSL端口上也重复出现问题(135,它是Hyper-V虚拟化)。最让我困惑的是,在重新启动建立连接的客户操作系统之后,在停止打开这些连接的软件之后,它们仍然标记为在客户端计算机上建立。我认为系统本身确实存在问题(并且与我们的Java代码无关),但究竟是什么问题......
更新3 问题是由TrendMicro的反病毒软件“Virus Buster”引起的。它阻止了连接正常关闭。
答案 0 :(得分:0)
注册频道在下一次select()
通话之前不会完全关闭。这是记录在某个地方,我找不到它。
请注意,您的trustAllCertificates()方法除了实现根本不安全之外没有任何用处,并且每个打开的套接字调用一次根本不应该打开它看起来完全没有意义。
答案 1 :(得分:0)
问题是由TrendMicro的反病毒软件“Virus Buster”引起的。它阻止了连接正常关闭。