When I create a socket:
Socket socket = new Socket(ipAddress, port);
It throws an exception, which is OK, because the IP address is not available. (The test variables where String ipAddress = "192.168.0.3"
and int port = 300
.)
The problem is: how do I set it to timeout for that socket?
When I create the socket, how do I reduce the time before I get a UnknownHostException
and get the socket to timeout?
You could use the following solution:
Hope it helps!
You can't control the timeout due to
UnknownHostException
. These are DNS timings. You can only control the connect timeout given a valid host. None of the preceding answers addresses this point correctly.But I find it hard to believe that you are really getting an
UnknownHostException
when you specify an IP address rather than a hostname.EDIT To control Java's DNS timeouts see this answer.
You don't set a timeout for the socket, you set a timeout for the operations you perform on that socket.
For example
socket.connect(otherAddress, timeout)
Or
socket.setSoTimeout(timeout)
for setting a timeout onread()
operations.See: http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html
Use the
Socket()
constructor, andconnect(SocketAddress endpoint, int timeout)
method instead.In your case it would look something like:
Quoting from the documentation
Use the default constructor for Socket and then use the connect() method.