I am trying to download a file from my local FileZilla Server with Java FTPSClient
running in Android emulator.
I\'ve written this helpercode to downloa
While I'm not familiar with Android Emulator, I assume that you need to connect to 10.0.2.2 to connect to the emulator host machine.
In an FTP passive mode, the server sends back an IP address to which the FTP client needs to connect to transfer a file (or a directory listing). As your FTP server listens on 127.0.0.1, it sends back that IP address. But 127.0.0.1 refers to the (emulated) Android host, in the context of your Android code. Hence the "connection refused".
This is pretty much similar to a common problem with connecting to an FTP server behind a NAT. See FTP server running on Port 2000 over NAT not working on Passive Mode
And the solution is hence the same:
Obviously this in turn makes the FTP server unusable for normal clients.
And you have correctly commented, this problem only arise when connecting from Android emulator to an FTP server running on emulator host.
Another solution is using FTPClient.setPassiveNatWorkaroundStrategy
. It accepts an implementation of HostnameResolver
interface. If you implement in a way that it translates 127.0.0.1 to 10.0.2.2, it will allow your Java code to connect even with out any change on the server.
public static class ServerResolverImpl implements HostnameResolver {
private FTPClient client;
public ServerResolverImpl(FTPClient client) {
this.client = client;
}
@Override
public String resolve(String hostname) throws UnknownHostException {
return this.client.getRemoteAddress().getHostAddress();
}
}