Boost: FTP client implemented by ASIO

Source: Internet
Author: User
Tags ftp commands printable characters ftp client ftp protocol
Document directory
  • Commands in FTP

Someone else's code was slightly modified. Boost1.50 and vs2008 can be compiled successfully.

----------- Test_ftp.cpp ---------------

// Ftp_asio.cpp: defines the entry point of the console application. //// # Include "stdafx. H "# pragma warning (Disable: 4996) # include <iostream> # include <istream> # include <ostream> # include <fstream> # include <string> # include <boost/ASIO. HPP> # include <boost/lexical_cast.hpp> using boost: ASIO: IP: TCP; using namespace STD; string strhost, strport; // obtain the object length long getfilelength (const string & stringline) {long ldfilelength = 0; size_t nbeginpos = stringline. find_first_of (""); size _ T nendpos = stringline. find_first_of ("\ r \ n"); STD: stringstream stream; string strlength = stringline. substr (nbeginpos, nendpos-nbeginpos + 1); stream <strlength; stream> ldfilelength; return ldfilelength ;} // obtain the value int getretcode (const string & stringline) {If (stringline. size () <3) {return-1;} size_t NPOs = stringline. find_first_of (""); STD: stringstream; string strcode = stringline. substr (0, NPOs); int nretcode = 0; stream <strcode; stream> nretcode; return nretcode;} // bool senddatacommand (TCP: Socket & socket, string strcommand, string & strresult) {boost: ASIO: streambuf request; Boost: ASIO: streambuf response; STD: String strline; STD: ostream request_stream (& request ); STD: istream response_stream (& response); strcommand + = ("\ r \ n"); cout <Endl <"command is:" <strcommand <Endl; request _ Stream <strcommand; Boost: ASIO: Write (socket, request); Return true;} // send the command to the FTP server bool sendcommand (TCP: Socket & socket, string strcommand, string & strresult) {boost: ASIO: streambuf request; Boost: ASIO: streambuf response; STD: String strline; STD :: ostream request_stream (& request); STD: istream response_stream (& response); strcommand + = ("\ r \ n"); cout <Endl <"command is: "<strcommand <Endl; request_st Ream <strcommand; Boost: ASIO: Write (socket, request); Boost: ASIO: read_until (socket, response, "\ r \ n"); STD:: Getline (response_stream, strresult); Return true;} bool gethostandport (string & strresult) {size_t nbegin = strresult. find ("("); size_t nend = strresult. find (")"); If (nbegin =-1 | nend =-1) return false; strhost = strresult. substr (nbegin + 1, nEnd-nBegin-1); nbegin = strhost. find_last_of (","); STRP ORT = strhost. substr (nbegin + 1, nend-nbegin + 1); int nport = 0, TMP = 0; TMP = boost: lexical_cast <int> (strport); strhost = strhost. substr (0, nbegin); nbegin = strhost. find_last_of (","); strport = strhost. substr (nbegin + 1, nend-nbegin + 1); nport = boost: lexical_cast <int> (strport); nport = 256 * nport + TMP; strport = boost :: lexical_cast <STD: String> (nport); Return true;} bool opencontrol (TCP: Socket & socket) {bool B Ret = false; string strresult; sendcommand (socket, "", strresult); STD: cout <strresult <Endl; cout <"RET code is: "<getretcode (strresult) <Endl; // send user // sendcommand (socket," USER anonymous ", strresult); sendcommand (socket," user 5xue ", strresult); STD: cout <strresult <Endl; cout <"User RET code is:" <getretcode (strresult) <Endl; /// send password // sendcommand (socket, "Pass anonymous", strresult); Sen Dcommand (socket, "Pass 5xue.com", strresult); STD: cout <strresult <Endl; cout <"User RET code is:" <getretcode (strresult) <Endl; // send type 1 sendcommand (socket, "type I", strresult); STD: cout <strresult <Endl; cout <"User RET code is:" <getretcode (strresult) <Endl; // send size // string strobject = "Incoming/processexplorer/procexp.exe "; string strobject = "upload/readme.txt"; // string strobject = "upload/ The first volume of the art of computer programming, vol. 1: Basic arithmetic example "; string strcommand (" size "); strcommand + = strobject; sendcommand (socket, strcommand, strresult); STD :: cout <strresult <Endl; cout <"User RET code is:" <getretcode (strresult) <Endl; long ldfilesize = getfilelength (strresult ); cout <"filesize is:" <ldfilesize <Endl; If (ldfilesize> 0) {Bret = true;} // send type 1 // sendcommand (socket, "Type I", strresult); // STD: cout <strresult <Endl; // Cout <"type 1 RET code is:" <getretcode (strresult) <Endl; // send pasvsendcommand (socket, "PASV", strresult); STD:: cout <strresult <Endl; cout <"pasv ret code is:" <getretcode (strresult) <Endl; Bret = gethostandport (strresult ); strcommand = "retr"; strcommand + = strobject; senddatacommand (socket, strcommand, strresult); Return Bret;} bool opendatachannel (TCP: Socket & data_socket) {bool Bret = false; boost: SiO2: streambuf response; // ASIO: error_code error; Boost: System: error_code error; If (response. size ()> 0) STD: cout <& response; ofstream file; file. open ("file.txt", ios_base: Binary); // read until EOF, writing data to output as we go. while (boost: ASIO: Read (data_socket, response, boost: ASIO: transfer_at_least (1), error) {STD: cout <& response; // file <& response;} file. close (); If (error! = Boost: ASIO: Error: EOF) // throw boost: ASIO: system_error (error); throw boost: System: error_code (error ); return Bret;} int main (INT argc, char * argv []) {// at least one boost: ASIO: io_service object boost: is required for network connection with ASIO :: ASIO: io_service; // we need to convert the server specified in the command line parameter to a node on TCP. // to do this, boost: ASIO: IP: TCP: resolver object TCP: resolver time_server_resolver (io_service); // a resolver object queries a parameter, and converts it to a list of nodes on TCP. // TCP :: Resolver: Query query ("192.168.1.111", "ftp"); TCP: resolver: Query query ("ftp.5xue.com", "ftp "); // you can use boost: ASIO: IP: TCP: resolver: iterator to iterate the node list. // The default iterator constructor generates an end iteratortcp: resolver: iterator endpoint_iterator = time_server_resolver.resolve (query); TCP: resolver: iterator end; // now we create a connected sockert, because the obtained node has both IPv4 and IPv6. // Therefore, we need to try them until we find one that can work normally. // This step makes our program independent from the IP version TCP: Socket so Cket (io_service); // boost: ASIO: error_code error = boost: ASIO: Error: host_not_found; Boost: System: error_code error = boost :: ASIO: Error: host_not_found; while (error & endpoint_iterator! = END) {socket. close (); socket. connect (* endpoint_iterator ++, error);} If (error) {// throw boost: ASIO: system_error (error); throw boost: System :: system_error (error);} // Commu with FTP serverbool bstate = opencontrol (socket); If (! Bstate) Return-1; TCP: Socket data_socket (io_service); // TCP: resolver: Query data_query ("192.168.1.111", strport); TCP: resolver :: query data_query ("ftp.5xue.com", strport); TCP: resolver: iterator data_endpoint_iterator = partition (data_query); error = boost: ASIO: Error: host_not_found; if (error & data_endpoint_iterator! = END) {data_socket.close (); data_socket.connect (* data_endpoint_iterator ++, error); cout <"data_socket.close ():" <error. value () <"\ t" <error. message () <Endl;} If (error) {// throw boost: ASIO: system_error (error); throw boost: System: system_error (error );} opendatachannel (data_socket); Return 0 ;}

 

-----------------------------------------

FTP command

FTP HELP

214-the following commands are recognized (* =>'s unimplemented ):

CWD xcwd cdup xcup SMNT * Quit port PASV

Eprt epsv allo * RNFR RNTO DELE MDTM RMD

Xrmd MKD xmkd PWD xpwd size syst help

Noop feat opts auth * CCC * conf * ENC * mic *

Pbsz * prot * type stru mode RETR stor STOU

Appe rest Abor user pass Acct * rein * List

Commands in the NLST stat site FTP protocol

17:00:25 | category: ftp | Tag: FTP command cwd pwd list port | large font size, small/medium subscription

4.1. FTP command (this refers not to the FTP command under the command line, but to the server and client communication in the Protocol)
4.1.1. Access Control commands
The following command specifies the access control flag (the authorization code is in brackets ):
User)
The parameter number indicates the user's telnet string. User tags are required to access the server. This command is usually the first command issued after the connection is controlled. Some hosts also require passwords and accounts. The server can receive new user commands at any time to change access control and (or) account information. This allows you to re-start the logon process, so the transmission parameters remain unchanged. The ongoing file transmission is completed under the previous access control parameters.
Password (PASS)
The parameter is a telnet string that marks the user password. This command follows the USER command, which is an indispensable step for access control on some sites. Therefore, passwords are important and cannot be displayed. The server cannot hide the passwords. Therefore, this task must be completed by the user's FTP process.
Account (ACCT)
 
A parameter is a telnet string that marks the user account. This command does not need to be related to users. Some sites may need accounts for logon, while others can restrict account permissions. In the latter case, this command can be sent at any time. Different responses can be different: When the logon requires account information, the response to the PASS Command is 332. In addition, if you do not need account information, the response to pass is 230. If you need account information later, the server will return 332 or 532, it depends on whether the command is saved or rejected.
Change working directory (CWD)
This command allows users to work in different directories or datasets without changing their logon or account information. The transmission parameters remain unchanged. A parameter is generally a directory name or a collection of system-related files.
Return to the previous directory (cdup)
This command requires the system to implement the directory tree structure, and its response is the same as that of CWD.
Structure loading (SMNT)
This command enables the user to load the data structure of another file system without changing the login or account information. The transmission parameters remain unchanged. A parameter is a file directory or a collection of system-related files.
Rein)
This command terminates the user and writes all I/O and account information, but the ongoing data transmission is not allowed to complete. Reset all parameters to control the connection opening. You can start the USER command again.
Log out (quit)
This command terminates the user. If there is no data transmission, the server closes the control connection. If there is data transmission, the server closes the control connection after receiving the transmission response. If the user process is transmitting data to different users and you do not want to disable and enable each user, you can use rein. The accidental shutdown of the control connection can cause the server to stop (Abor) and log out (quit ).
4.1.2. transmission parameter command
All data transmission parameters have default values. The server must record the default value, which can be sent in any order after FTP service requests. The following command transfers parameters:
Data port)
 
The parameter is the data connection port to be used. Generally, no command response is required. If you use this command, you need to send a 32-bit IP address and a 16-bit TCP port number. The above information is transmitted in decimal format with a comma (,), as shown in the following example:
Port H1, H2, H3, H4, p1, p2
H1 is the maximum 8-bit IP address.
Passive (PASV)
This command requires the server DTP to listen on the specified data port and enter the passive request receiving status. The parameter is the host and port address.
Type)
The parameter specifies the type. For some types, the second parameter is required. The first parameter is defined by a single Telnet character. The second parameter is a decimal integer that specifies the byte size. The parameters are separated by <SP>. The format is as follows:
The default type is ASCII non-printable characters. If the parameter is not changed and only the first parameter is changed later, the default value is used.
File structure (stru)
The parameter is a telnet character code that specifies the file structure. The following is the code and its meaning:
F-file (non-record structure), which is the default value
R-record Structure
P-Page Structure
Transmission Mode)
The parameter is a telnet character code that specifies the transmission mode. The following is the code and its meaning:
S-stream (default)
B-block
C-compression
4.1.3. FTP service commands
The FTP service command defines the file transfer or file system functions requested by the user. The parameter of this command is usually the path name, and its syntax must be consistent with the specifications of the server. The Recommended default value is the recently specified Device directory or directory. There is usually no limit on the command order. Only the "RENAME from" command must be followed by "RENAME to", and the restart command must be followed by the interrupt service command. Responses to service commands are usually transmitted over data connections. The following is a specific command:
Get file (RETR)
This command allows the server DTP to send a copy of the file in the specified path to the server or user DTP. The status and content of files on the server are not affected.
Save (stor)
This command allows the server DTP to receive the data transmitted over the data connection and save the data in the Server File. If the file already exists, the original file will be overwritten. If the file does not exist, create a new file.
Unique storage (STOU)
This command is similar to stor. The file name in this directory must be unique. The response to this command must include the generated user name.
Additional (APPE)
It is similar to the stor function, but if the file already exists in the specified path, the data is appended to the end of the original file. If the file does not exist, the new file is created.
Allocation (allo)
This command is used to allocate sufficient storage space for newly transferred files on some hosts. The parameter is the number of logical bytes in decimal format. For a record or page structure, the maximum page or record size is also required, which is specified in decimal in the second parameter. The second parameter is optional. If it exists, it is separated from the first parameter by the Telnet character <SP> r <SP>. After the STOR or APPE Command, this command serves as Noop for machines that do not need to allocate storage space.
Start again (rest)
The parameter field indicates the point where the server needs to start again. This command does not transfer files, but skips the data after the specified point. After this command, it should be followed by other FTP commands that require file transmission.
Rename (RNFR)
This command is the same as what we use in other operating systems, except that the new file name must be specified with "RENAME.
Rename it to (RNTO)
This command is used together with the preceding command to rename the file.
Abandon (Abor)
This command notifies the service to abort the previous FTP command and related data transfer. If the previous operation has been completed, no action is returned, and 226 is returned. If not, 426 is returned and 226 is returned. Close the control connection. The data connection is not closed.
Delete (DELE)
This command deletes objects in the specified path. The user process is responsible for the deletion prompt.
Delete directory (RMD)
This command deletes the directory.
Create directory (MKD)
This command creates a new directory in the specified path.
Print the working directory (PWD)
In the response, the current working directory is returned.
List)
Server transport list to passive DTP. If a directory or many files are specified in the path, the list of files in the specified path is returned. If the path name specifies a file, the server returns the current information of the file. The parameter is null, indicating the current working directory or default directory of the user. Data is transmitted in ASCII or ebcdic. You must confirm this. Because the file information varies by system, it cannot be automatically used by the program, but human users need it.
Name List (NLST)
The server transfers the directory table name to the user. The path name should specify the directory or the file group description specified by other systems. The null parameter indicates the current directory. The file name data stream returned by the server is transmitted in ASCII or ebcdic format and separated by <CRLF> or <NL>. The returned information can be further processed by the program.
Site Parameters)
The server is used to provide the server system information. The information varies with the system. The format is provided in the help site command response.
System (syst)
Used to determine the operating system running on the server.
Status (STAT)
This command returns the control connection status, which can be sent during file transfer and the server returns the status of the operation. It can also be sent between file transfers. At this time, the command has a parameter, and the parameter is the path name. The function of this command is similar to that of the LIST command in addition to data transfer over the control connection. If a part of the path is specified, the server returns a file name or description-related attribute. If no parameter exists, the server returns the status information of the FTP process on the server, including the current value and connection status of the transmission parameter.
Help)
There is no difference in the help of this command in common systems. The response type is 211 or 214. We recommend that you use this command before using the USER command.
Wait (Noop)
This command does not generate any actual action. It only causes the server to Return OK.
FTP uses Telnet for communication over the control connection, so you have the opportunity to read the relevant protocol description. The following sections will be helpful. The following describes the command response and detailed information about the command. FTP commands can be divided into access control tags, data transmission parameters or FTP service requests. Specific commands (such as Abor and STAT) can be transmitted over control connections during data transmission. Some servers cannot monitor data and control links at the same time, so they must take additional measures. Pay attention to the following suggestions:
1. the user system inserts the "interrupt process" (IP) Information of telnet into the Telnet stream;
2. the user system sends the "synch" signal for telnet;
3. the user system inserts commands (such as Abor) into the Telnet stream;
4. After receiving the IP address, the server PI finds only one FTP command in the Telnet stream.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.