Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), 1000);
Quoting from the documentation
connect
public void connect(SocketAddress endpoint, int timeout) throws IOException
Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.
Parameters:
endpoint - the SocketAddress timeout - the timeout value to be used in milliseconds.
Throws:
IOException - if an error occurs during the connection SocketTimeoutException - if timeout expires before connecting IllegalBlockingModeException - if this socket has an associated channel, and the channel is in non-blocking mode IllegalArgumentException - if endpoint is null or is a SocketAddress subclass not supported by this socket
SocketAddress sockaddr = new InetSocketAddress(ip, port);
// Create your socket
Socket socket = new Socket();
// Connect with 10 s timeout
socket.connect(sockaddr, 10000);
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.