Search code examples
javaftpftp-clientapache-commons-net

How to enter FTP server's passive mode or active mode through FTPClient


Client is entering passive mode first, because I don't know if the Remote FTP-server is active-mode or passive-mode.

Generally, one enters passive mode first.

The code is as follows:

FTPClient ftpClient = new FTPClient();
ftpClient.connect(ip,port);
ftpClient.login(id,pw);
ftpClient.enterLocalPassiveMode();
...
(occur mode error)
(I use try-catch in case an error occurs)
(active mode reconnect)
...
ftpClient.logout();
ftpClient.disconnect();
ftpClient.connect(ip,port);
ftpClient.login(id,pw);
ftpClient.enterLocalActiveMode();

I want to hear the right thing to do with mode processing like this.

I'm using FTPClient (Apache Commons Net).


Solution

  • In active mode FTP the server must open a TCP connection back to the client; unless your client is directly on the internet (with no firewall or address forwarding) then active mode will not work.

    In contrast, passive mode FTP does not open a TCP socket from the server to the client and will work in both cases (direct internet connection, and internet connection through address forwarding).

    Most computers are behind a firewall and use address forwarding, so passive mode is usually the way to go.