Search code examples
javajakarta-eeftpftp4j

Java ftp4j - List files in FTP server when connecting in amn active mode


I am using ftp4j library to implement my FTP clients however a server that I am trying to connect accept connections only in active mode.

So when I am trying to list remote files i am getting:

ERROR : Error in Connecting to Remote Machine... Hence exitting...
it.sauronsoftware.ftp4j.FTPException [code=501, message= Server cannot accept argument.]
at     it.sauronsoftware.ftp4j.FTPClient.openActiveDataTransferChannel(FTPClient.java:3600)
at it.sauronsoftware.ftp4j.FTPClient.openDataTransferChannel(FTPClient.java:3551)
at it.sauronsoftware.ftp4j.FTPClient.listNames(FTPClient.java:2335)
at com.npap.network.TranferFileFtp4j.listRemoteFilesFtp1(TranferFileFtp4j.java:999)

Here is the code:

...
//connect to server method - in active mode!
ftpClient = Ftp4jUtility.connect1(SERVER_MACHINE, PORT, SERVER_USERNAME, SERVER_PASSWORD);

try {
    ftpClient.changeDirectory(config.getFtpRemoteFolderReports());    
    log.info("Changed directory to: " + config.getFtpRemoteFolderReports());
} catch (FTPException | FTPIllegalReplyException | IOException | IllegalStateException e) {
    e.printStackTrace();
}

String[] filesList = ftpClient.listNames();
    for(String f: filesList) {
        log.info("fetched file: " + f);
        tmpAllRemoteFiles.add(f);
}

Any way to list remote files when connecting in active mode?


Solution

  • Yes, you can use the .listNames() in the active mode.

    The problem is likely that the server cannot connect back to your client to open the data connection. You have to open the ports from FTP data connection range on your local firewall (if any), as well as route the incoming connections on your NAT (if any).

    Configuring the active mode FTP is cumbersome and is rarely used.

    Learn (my) article about required network configuration in respect to FTP active mode.

    The 501 error code comes from the FTP server (IIS likely). You will find lots of similar problems, if you google for "501 Server cannot accept argument".

    There's nothing wrong with your code. It's either the network configuration or server-side problem.