如何从 FTP 服务器读取多行响应?

How to read multiline response from FTP server?

我正在用 C 编写 FTP 客户端程序。我正在使用阻塞套接字。我已将 recv () 放入 while 循环中,当最后两个接收到的字符为 \r\n 时我将其中断。我可以在某些服务器上 运行 它但它不会在某些服务器上读取整个消息,例如 ftp.secyt.gov.ar.

我认为问题是因为来自服务器的消息同时包含 \r \n 个字符。

遇到这种情况应该怎么处理?

将用户名和密码发送到服务器 ftp.secyt.gov.ar 后,我想打印从服务器收到的消息。

password = getpass("Password: ");
sprintf(pass, "PASS %s\r\n",password);

send(sockfd, pass, strlen(pass), 0);

while((no_of_bytes = recv(sockfd, message_from_server, MAXSZ, 0)) > 0)
{
    message_from_server[no_of_bytes] = '[=11=]';
    printf("%s\n", message_from_server);

    if (message_from_server[no_of_bytes-2] == '\r' &&
        message_from_server[no_of_bytes-1] == '\n')
        break;
}

服务器发送此消息:

230-=====================================================================

    BIENVENIDOS AL SERVIDOR FTP DE LA MINCyT   
             ----------------------------------------

Usuario anonymous, desde la maquina ::ffff:116.203.73.60, gracias por
utilizar el FTP del Ministerio de Ciencia, Tecnologia e
Innovacion Productiva.

Para sugerencias, consultas o informacin adicional nuestros correos 
electrnicos son:
                     webmaster@mincyt.gov.ar

=========================================================================
230 User anonymous logged in.

但它只是打印:

230-=====================================================================

您的代码从服务器读取一行(以 \r\n 结尾的字符串)。

但是根据 FTP 规范,FTP 响应可以是多行的。

查看 RFC 959, section 4.2 FTP Replies:

Thus the format for multi-line replies is that the first line will begin with the exact required reply code, followed immediately by a Hyphen, "-" (also known as Minus), followed by text. The last line will begin with the same code, followed immediately by Space , optionally some text, and the Telnet end-of-line code.

For example:

 123-First line  
 Second line  
   234 A line beginning with numbers  
 123 The last line

The user-process then simply needs to search for the second occurrence of the same reply code, followed by (Space), at the beginning of a line, and ignore all intermediary lines. If an intermediary line begins with a 3-digit number, the Server must pad the front to avoid confusion.


另见 How to know the end of FTP Welcome message