SMTPClient 为开放端口设置超时

SMTPClient set timout for an open port

我的问题是:我需要发现一个 IP 和端口是否是 运行 SMTP 服务。 为此,我使用 SMTPClient 尝试打开一个连接。我正在使用下面的代码。

    private static boolean validateSMTP(String ip, int port, int timeOut) {
    SMTPClient smtp = new SMTPClient();

    try {
        smtp.setConnectTimeout(timeOut);            
        smtp.connect(ip, port);
        return true;

    } catch (SocketException e) {
        LogAplication.Warning("Ops... something wrong", e);
    } catch (IOException e) {
        LogAplication.Warning("Ops... something wrong", e);
    }
    finally{
        smtp = null;
    }

    return false;
}

它工作正常,我得到了预期的结果,但超时一直是我的问题。 例如:如果我尝试 ip: 127.0.0.1 和端口 80(IIS 打开端口),连接步骤需要很长时间(远远超过超时中定义的时间)来抛出异常

java.net.SocketException: Connection reset

如何为这种情况设置超时?或者 exist 是进行简单测试的另一种方法?

看完后grepCode, I found this for method connect(string host, int port):

Opens a Socket connected to a remote host at the specified port and originating from the specified local address and port. Before returning, _connect Action() is called to perform connection initialization actions.

由于端口被其他服务打开,socket被打开,并没有造成timeOut(by socket),而是"connectAction()"抛出了异常 所以我需要为我的 SMTPClient 设置一个全局超时,它由套接字连接和 "connectAction()" 内部使用。我这样做是为了解决我的问题:

smtp.setDefaultTimeout(timeOut);

有了这个,现在我得到了预期的结果,打开了抛出异常的端口,当然还有 SMTP 服务的成功连接。