我是 C 和套接字新手。我用 C 语言编写了一个简单的 ftp 服务器和客户端。最初它可以工作,但是当我向 pwd 添加一个选项时,它坏了。它不是服务器等待键盘输入,而是在没有输入的情况下运行。我正在使用默认设置,所以它应该被阻止。此外,我已将 MSG_WAITALL 添加到我的 recv() 中,但没有任何变化。我究竟做错了什么?
相关的服务器代码如下(这是为客户端生成文件列表然后等待文件名通过客户端输入传输的部分)。
//wait for ls command
if ((numbytes = recv(new_fd, buf, MAXDATASIZE - 1, 0)) == -1) {
perror("recv");
exit(1);
}
//remove newline from fgets
strip_newline(buf, sizeof(buf));
int result = strncmp(cmd, buf, 2);
if (result == 0){
//list files
file = fopen ("temp", "wb"); //we store our file listing in this temp file
char cmd_buffer[LENGTH];
dp = opendir ("./");
if (dp != NULL){
while (ep = readdir (dp))
fprintf(file, "%s\n", ep->d_name);
(void) closedir (dp);
}else
perror ("Couldn't open the directory");
//send our list down the wire
fclose(file);
file = fopen ("temp", "rb");
bzero(buffer, LENGTH);
while ((res = fread(buffer, sizeof(char), LENGTH, file)) > 0){
if(send(new_fd, buffer, res, 0) < 0){
fprintf(stderr, "ERROR: Failed to send file %s. (errno = %d)\n", buf, errno);
break;
}
bzero(buffer, LENGTH);
}
fclose(file);
//read filename
if ((numbytes = recv(new_fd, buf, MAXDATASIZE - 1, MSG_WAITALL)) == -1) {
perror("recv");
exit(1);
}
//remove newline from fgets
strip_newline(buf, sizeof(buf));
printf("Trying to open %s\n", buf);