【发布时间】: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 套接字上,您可以选择一个 或 另一个。