Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SSL Socket connect timeout

How can I configure connect timeout for SSL Sockets in Java?

For plain sockets, I can simply create new socket instance without any target endpoint using new Socket(), and then call connect(SocketAddress endpoint, int timeout) method. With SSL sockets, I cannot create new SSLSocket() and SSLSocketFactory.getDefault().createSocket() method with no endpoint throws UnsupportedOperationException with Unconnected sockets not implemented message.

Is there a way to use connect timeouts for SSL Sockets in Java, using standard java libs only?

like image 427
Peter Štibraný Avatar asked Apr 19 '11 11:04

Peter Štibraný


People also ask

What is SSL connection timeout?

The handshake timeout specifies the duration in time that the system tries to establish an SSL connection before halting the operation. New Behavior. Beginning in BIG-IP 11.2. 0, the default SSL handshake timeout is 10 seconds and can be configured by users.

How do I set socket timeout?

You can make an instance of a socket object and call a gettimeout() method to get the default timeout value and the settimeout() method to set a specific timeout value. This is very useful in developing custom server applications.

What is ideal socket timeout?

Re: Recommended Value for http socket timeout Given that on Policy server the default idle timeout for socket is 10min, I think 10 min is good vlaue for it.


3 Answers

I believe you could use your current approach of creating the Socket and then connecting it. To establish SSL over the connection you could use SSLSocketFactory.createSocket

Returns a socket layered over an existing socket connected to the named host, at the given port.

This way you get full control over the connection and then you negociate setting up SSL on top of it. Please let me know if I misread your question.

like image 173
cnicutar Avatar answered Sep 28 '22 06:09

cnicutar


With java 1.7 the following does not throw the exception stated in the question:

String host = "example.com";
int port = 12345;
int connectTimeout = 5000;
SSLSocket socket = (SSLSocket)SSLSocketFactory.getDefault().createSocket();
socket.connect(new InetSocketAddress(host, port), connectTimeout);
socket.startHandshake();

so it's business as usual.

like image 29
predi Avatar answered Sep 28 '22 06:09

predi


Elaborating on @predi's answer, I found that I needed to use "setSoTimeout" too. Otherwise sometimes it gets stuck in the handshake (on very unstable connections):

    final int connectTimeout = 30 * 1000;
    SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
    socket.setSoTimeout(connectTimeout);
    socket.connect(new InetSocketAddress(hostAddress, port), connectTimeout);
    socket.startHandshake();
    socket.setSoTimeout(0);`
like image 42
Gibezynu Nu Avatar answered Sep 28 '22 06:09

Gibezynu Nu