FTP upload/download over TCP

FTP is standard protocol to transfer files by using separate control and data connections between the client and server. There are two operating modes - active and passive. Details on the available commands and how to use them can be found on the web. Here, a working C++ code is shown which downloads and uploads files in both modes. To simplify the work, Boost library is used for dealing with sockets. For the purpose of samples, FTP server on this domain is used, but the username and password in the source code are hidden for obvious reasons.:) To use them, just replace server parameters to FTP commands with your own. In all samples, commands and file sizes are small enough to be hold in given buffers with single send/receive commands. For the larger ones, send/receive must be executed while all data is sent/received, find a socket tutorial for that.


Downloading in passive mode means that a socket connects to the FTP server and retreives a given file at the given directory. Two sockets are used - one for executing commands, and other to get the file. Those two connections are performed simultaneously in two threads.

download_pasv.cpp

Downloading in active mode means that the FTP server connects to the client's machine on the given port. So, client gives it address in the local network (192.168.1.102) and the port 50000. FTP server will refuse the given address and use the public IP address. (If the client is behind proxy or NAT, probably the active method will not work.) When client accepts server's connection, it can receive the content over socket. Again, one thread uses socket for sending commands and another to receive the file.

download_act.cpp


Uploading in passive mode is similar to downloading in passive method except that file is sent over socket.

upload_pasv.cpp


Finally, uploading in active mode is similar to downloading in active method except that file is sent over socket.

upload_act.cpp


Samples are tested under Linux 2.6 64bit/gcc 4.5.2/boost 1.45 compiled as specified in the Makefile.

Makefile

ready.

10 print "mail: contact at alepho.com | skype: karastojko | stackoverflow: karastojko | github: karastojko"
20 print "(c) 2009-2023 www.alepho.com"