A short guide about ftp ports

The ftp protocol isn't as simple as most others.

FTP uses two different ports; one for the session and another for the data transfer.

As standard these are port 21 and port 20 respectively.

Now comes the complication. In standard "active" mode, you log into the ftp server, port 21 (session port), select the file you want and start the download. The server then opens a connection from 20 to a random port on your machine to start transporting the data. The port it uses on your machine is negotiated in the session (you should see some command like "PORT 213.33.241.15,3353" go past).

Now this is all fine and dandy, but what about where the client is behind a firewall (or NAT)? You'll be able to log in, but the data transfer will never start, as the incoming data connection is blocked (or dropped). Well that's where passive mode comes in.

In passive mode the session port is the same, 21 on the server. However this time when the data transfer is started the client makes the connection from port 20 to a random port on the server (negotiated with the PORT command).

This eliminates the firewall problem for the client, but means the firewall on the ftp server must allow connections to any non-privileged port (above 1024) on itself from port 20 on a client. This will allow a client behind a firewall to work, though you have to use passive mode, if incoming connections are blocked, active mode will always fail.

This then becomes a problem if the ftp server is behind NAT, as the router has no idea where to send the incoming ftp-data connections as they will be targeted at random ports. Which is where stateful NAT devices are needed. They monitor ftp-session packets for the negoiated ports that will be in use and direct them as needed. Various NATing routers support this feature, but often use different names, such as "ftp fixup".

SCP/SFTP is a much better alternative, uses only one TCP port and is much more secure.

imux.net