【问题标题】:socket send() replying with leading "%s "套接字发送()以“%s”开头
【发布时间】:2015-02-08 05:32:12
【问题描述】:

我正在尝试使用以下代码实现一个 ftp 服务器:

 64         if (command_sock == -1){
 65                 printf("error accepting socket connection: errno = %d\n", errno);}
 66         else{printf("connection accepted\n");}
 67 
 68         send(command_sock, "220 FTP Server ready\n", 25, 0);
 69 
 70         int image_mode = 0; //not set to "I"
 71         int file_str = 1; //file mode by default
 72 
 73         while(1){
 74                 recv(command_sock, buffer, 512, 0);
 75                 sscanf(buffer, "%s %[^\n]s", command, arg);
 76                 printf("command = \"%s\"\n", command);
 77                 printf("arg = %s\n", arg);
 78 
 79
 80                 if(strcmp(command, "USER") == 0){
 81                         send(command_sock, "230 user logged in\n", 35, 0);
 82                 }
 83                 else if(strcmp(command, "QUIT") == 0){
 84 
 85                         close(command_sock);
 86                         close(send_1);
 87                         goto listen;
 88 
 89 
 90                 }

但是当我尝试登录时它失败了,因为第 81 行确实发送了“%s 230 用户登录\n”。

root@nodeforcetwo:/home/rustyventure/opsys/mac_5# ftp
ftp> open 127.0.0.1 3500
Connected to 127.0.0.1.
220 FTP Server ready
Name (127.0.0.1:rustyventure): rusty
%s 230 user logged in
Login Failed

谁能明白为什么,我在这里不知所措。

谢谢

【问题讨论】:

    标签: sockets ftp send


    【解决方案1】:

    在第 68 行中,您发送了 25 个字节,但您要发送的字符串仅包含 21 个字节。您最终会在该字符串常量之后发送额外的 4 个字节的内存中的任何内容。

    【讨论】:

      【解决方案2】:
      "220 FTP Server ready\n"
      

      是21字节,不是25,但是FTP中的行终止符是\r\n,不是\n,所以应该是:

      send(sock, "220 FTP Server ready\r\n", 22, 0);
      

      您还犯了一个常见错误,即忽略recv() 返回的计数。可以是:

      • -1,表示错误
      • 0,表示流结束:对端已断开连接
      • > 0,表示实际传输的字节数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-08
        • 2015-07-28
        • 1970-01-01
        • 2011-09-05
        • 1970-01-01
        相关资源
        最近更新 更多