Error “227 Entering Passive Mode”/“Connection refused” when downloading from local FTP server in Android emulator

后端 未结 1 1808
感动是毒
感动是毒 2021-01-16 12:10

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

相关标签:
1条回答
  • 2021-01-16 12:29

    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:

    • In FileZilla Server Interface, go to Edit > Settings > Passive mode settings > IPv4 specific > External Server IP Address for passive mode transfers. And enter 10.0.2.2.
    • Maybe you will also need to uncheck "Don't use external IP for local connections".

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题