edtFTPj/Free - Open-source FTP library for Java | Download
 How to use active or passive mode

In the FTP protocol, data transfers are made on a different connection to the control connection - and a new connection is made for each data transfer or directory listing.

Data connections can be made in two different ways - the server initiating the connection (active mode) or the client initiating the connection (passive mode). For more discussion on connect modes, see Active and Passive Modes. The connect mode has certain implications for FTP'ing through firewalls. If problems are experienced using one mode, the alternative mode should be tried.

Active Mode

To use active mode, the advanced settings object must be obtained via getAdvancedFTPSettings(), followed by setConnectMode(), supplying the ACTIVE mode as shown:

ftp.getAdvancedFTPSettings().setConnectMode(FTPConnectMode.ACTIVE);

In active mode, the client supplies the port number to which the server connects. This is normally a random port, but a port range can be specified (for example a permissable range that is configured in a firewall). Use the AdvancedFTPSettings.setActivePortRange() method to set the range, e.g.

ftp.getAdvancedFTPSettings().setActivePortRange(61500, 61510);

The port number being sent to the server can be found from the log file (in DEBUG mode), looking for the PORT command, e.g.

PORT 151,134,10,195,240,68

The first four numbers are the IP address, and the last two form the port number. To calculate the port number that the server will try to connect to, multiple the first port number by 256 (2^8), and then add the second port number. In the example it will be 240*(2^8) + 68, yielding a port number of 61508.

Passive Mode

To use passive mode, the setConnectMode()
method should be used, supplying the PASV type as shown.

ftp.getAdvancedFTPSettings().setConnectMode(FTPConnectMode.PASV);

If problems are being experienced with file transfers and directory listings (both of which use a new data connection each time), it is likely that a firewall is preventing the creation of the data connection. Try swapping from active to passive modes, or vice versa.