套接字编程:错误地址在循环中使用时read()出错

时间:2015-01-21 18:40:52

标签: c sockets file-descriptor

我试图将FTP Server作为赋值的一部分来实现,我编写了以下代码来实现GET Command,它基本上从服务器读取file1并将其存储在file2中。

int getCommandImpl(int clientSocket, char *file1, char *file2){
char *messageContent;
char buffer[256], userCommand[256], *tempString ;
int messageHead, endOfTransfer =0;
int messageLength;
sprintf(userCommand, "GET %s", file1);
messageLength = write(clientSocket,userCommand,strlen(userCommand));
if(messageLength <0){
    perror("Error sending data to server in RETR");
    return 0;
}
FILE *fp;
fp = fopen(file2, "w");
if(fp==NULL){
    printf("%s Can not be created\n", file2);
    return 0;
}
printf("Writing to file %s\n", file2);
while(!endOfTransfer){
    messageLength = read(clientSocket, buffer, strlen(buffer)-1);
    if(messageLength == -1){
        perror("GET: Error in read() ");
        break;
    }
    //puts(buffer);
    printf("Buffer is %s with len %d\n", buffer, strlen(buffer));
    tempString = strdup(buffer);
    messageHead = atoi(strtok(tempString, " "));
    messageContent = strtok(NULL, " ");
    if(messageHead == 0 && strlen(messageContent)==0){ //End of file transfer
        endOfTransfer = 1;
        break;
    }
    fwrite(messageContent, sizeof(char), sizeof(messageContent), fp);
    memset(buffer,0,sizeof(buffer));
    printf("Buffer is %s with len %d\n", buffer, strlen(buffer));
}
fclose(fp);
return 1;
}

运行它时,我总是收到错误“GET:read()中的错误:错误的地址”。如果我删除声明

memset(buffer,0,sizeof(buffer));

我遇到了分段错误。我假设错误与第二次迭代中字符串缓冲区为空有关。 任何帮助解决这个问题将受到高度赞赏。

0 个答案:

没有答案