Search code examples
ftpftp-clientunix-socket

How to read multiline response from FTP server?


I am writing FTP client program in C. I am use blocking socket. I have put recv () in while loop and I break it when last two received characters are \r\n. I am able to run it on some servers but it doesn't read whole message on some servers like ftp.secyt.gov.ar.

I think the problem is because of the messages from server which contains characters \r \n together.

How should I deal with such case?

After sending the user name and password to server at ftp.secyt.gov.ar, I want to print the message received from server.

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] = '\0';
    printf("%s\n", message_from_server);

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

Server sends this message:

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.

But it is printing only:

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

Solution

  • Your code reads a line (a string terminated by \r\n) from the server.

    But an FTP response can be multi-line, according to the FTP specification.

    See the 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.


    See also How to know the end of FTP Welcome message.