1

这是使用套接字进行网络通信的 FTP 客户端应用程序的一部分。在向 FTP 服务器发送命令之前,我想将命令缓冲区初始化为零 - 没有机会将新命令与可能位于缓冲区末尾的任何旧字符混合(在新命令之后和'\0'.

//global buffers msg[1024] and cmd[16]
void sendCommand(int client_socket, char* command, size_t cmd_len) {
    int in, out;
    memset(&msg, 0, sizeof(msg));
    memset(&cmd, 0, sizeof(cmd));
    strncpy(cmd, command, cmd_len); //
    printf("Command: %s\n", cmd);   //debugging prompt
    out = send(client_socket, cmd, sizeof(cmd), 0);
    sleep(1);
    in = recv(client_socket, msg, sizeof(msg), 0);
    sleep(1);
    printf("received %d bytes: %s\n", in, msg);  //debugging prompt
}

编辑:以下是上述函数的调用:

sendCommand(client_socket, "USER anonymous\r\n", sizeof("USER anonymous\r\n"));

问题是:缓冲区真的变空了,然后被命令填满,但服务器无法识别某些命令(例如 PASV)。问题出在代码中,因为如果我尝试注释掉,memset(&cmd, 0, sizeof(cmd));我会得到当前命令的预期结果加上缓冲区尾部的错误 500 Unknown commandcmd

这是来自服务器的示例答案:

Command: USER anonymous
received 720 bytes: 331 Please specify the password.
Command: PASS dummy    
received 720 bytes: 230-FFFFF III TTTTTT  Welcome!
230 Login successful.
500 Unknown command.    //tail of old data
command: PASV    
received 94 bytes: 227 Entering Passive Mode (147,229,9,30,40,184).
500 Unknown command.    //tail of old data
500 Unknown command.    //tail of old data
command: QUIT    
received 14 bytes: 221 Goodbye.

提前致谢!

4

2 回答 2

1

The error was incorrect string length. 1) No NULL at the end of string is needed. 2) The only correct end of line is CRLF for FTP 3) Now I use strlen instead of sizeof

于 2014-02-26T18:42:57.383 回答
0

您是否将 /r 放在命令的末尾?并确保在 strncpy cmd_len 中将 /r 包含在长度中

于 2014-02-24T08:10:41.183 回答