Timeout ignored with wrong ip

I’m working on an Android app (Java 8, apache.commons.net.ftp 3.6, Min: API 24/target: API 27) that connects to an FTP server but I’m experiencing a weird problem:

If I connect to one of the public test servers (e.g. speedtest.tele2.net) or the IP address directly (e.g. 10.1.1.123), it works fine.

If I add a typo in a “normal” address on purpose (e.g. sspeedtest.tele2.net), I get the expected java.net.UnknownHostException but if I add a typo to an IP address, no matter if it’s in the same network or not (e.g. 10.1.1.223), nothing else happens – no exception, no error, no result, even after the set timeout time has passed.

Code:

FTPClient f = new FTPClient();
f.setDefaultTimeout(5000); //5 seconds

try {
    f.connect(url,port);
    boolean b = f.login(username,password);
    Log.d(TAG,"logged in="+b+", connected="+f.isConnected());
} catch (IOException e) {
    e.printStackTrace();
}

I let it run a little bit longer and finally, after 1 minute and 16 seconds an exception was thrown:

W/System.err: java.net.ConnectException: Connection refused

I’ve tried this multiple times and the exception always seems to be thrown after 1:16.

How do I make this respect the default timeout too? Is there a different one I have to use?

Answer

You’re setting a timeout for receiving data. The timeout for opening a connection is separate, and set with the setConnectTimeout(int connectTimeout) method:

FTPClient f = new FTPClient();
f.setConnectTimeout(5000); // 5 second timeout to open connection
f.setDefaultTimeout(5000); // 5 second timeout when receiving data

If you get “connection refused” that means the IP address is actually used by some host in the network. If there was nothing at that address, you would get an error more along the lines of “no route to host”.

Leave a Reply

Your email address will not be published. Required fields are marked *