【问题标题】:Reading a socket读取套接字
【发布时间】:2017-05-21 13:53:54
【问题描述】:

我正在尝试模拟一个小型 ftp 服务器来训练自己,通过接受来自客户端的连接并与良好的回复进行通信并完成所要求的任务。但我不明白为什么我的服务器在读取套接字以获取客户端命令时总是遇到错误。我认为这可能是因为 getline() 但我不明白为什么会这样

这里是“接受”函数

    static int              my_startserver(char *path, int ssock)
    {
      int                   csock;
      struct sockaddr_in    addr;
      socklen_t             size;

      size = sizeof(&addr);
      printf("Server ready\n");
      while (42)
        {
          if ((csock = accept(ssock, (struct sockaddr*)(&addr), &size)) == -1)
            return (my_error(6, NULL, ssock));
          printf("New connection detected\n");
          if (fork() == 0)
            {
              close(ssock);
              my_newconnexion(my_getdata(csock, path));
            }
          else
            close(csock);
          printf("Waiting for new connexion\n\n");
        }
      return (0);
    }

static t_data   *my_getdata(int fd, char *path)
{
  t_data        *data;

  if (!(data = malloc(sizeof(t_data*))))
    return (NULL);
  else
    {
      if (!(data->fp = fdopen(fd, "r+")))
        {
          write(fd, "540 A stream creation failed.\r\n", 31);
          free(data);
          return (NULL);
        }
      data->fd = fd;
      data->path = path;
    }
  printf("Service ready\n");
  fprintf(data->fp, "220 Service ready for new user.\r\n");
  return (data);
}

这是在分叉后处理与客户端连接的函数

void    my_newconnexion(t_data *data)
    {
      char  *line;

      if (!data)
        return;
      line = NULL;
      printf("Waiting for command\n");
      while (getline(&line, NULL, data->fp) > -1)
        {
          printf("Command: %s\n", line);
          if (my_getcommand(data, line, strlen(line) - 2))
            {
              my_treatcommand(data);
              free(data->cmd);
              free(data->par);
            }
          free(line);
          line = NULL;
          printf("Waiting for command\n");
        }
      my_quit(data, -1);
    }

【问题讨论】:

  • if (!(data = malloc(sizeof(t_data*)))) -->> if (!(data = malloc(sizeof *data))) 你在这里分配了指针的大小。另外:上次我检查时,FTP 使用的是 UDP 套接字。
  • @wildplasser:据我所知Standard FTP protocol 对两种通道都使用 TCP:控制和数据。
  • @alk 好的。那么,也许我把它和 tftp 混淆了。
  • 哦,谢谢,我没有注意到那个错误。但它并没有解决问题,它的行为仍然相同。至于 UDP 套接字,如果您在创建套接字时使用 PF_INET,它涵盖了包括 UDP 在内的大多数 Internet 协议。
  • TCP 是 TCP,UDP 是 UDP。在 one 套接字上,您可以选择一个 另一个。

标签: c server ftp


【解决方案1】:

好的,所以我用一个自制函数替换了 getline(),它做同样的事情,但来自文件描述符(套接字),所以我不必用 fdopen 从它打开文件指针来将它提供给 getline现在它完美地工作了。

【讨论】:

  • 请编写解决方案的代码,而不仅仅是文字解释
猜你喜欢
  • 1970-01-01
  • 2017-10-19
  • 2012-10-15
  • 2011-10-29
  • 1970-01-01
  • 2016-08-10
  • 2019-04-02
  • 2013-10-12
相关资源
最近更新 更多