Home > front end >  TCP send a file data from client to server problem: different checksum on file
TCP send a file data from client to server problem: different checksum on file

Time:12-07

I try to transfer a data size of around 100MB over a TCP ipv4 connection socket.

I calculate the CheckSum in the client before sending it to see what the checksum is.

After sending the data file to the server and the server writes it to a new file I calculate again the checksum and I can see a differents.

I think is probably with my send and receive functions.

The Sender function used in CLIENT :

void send_file(FILE *fp, int sockfd) {
    int n;
    char data[SIZE] = {0};

    while (fgets(data, SIZE, fp) != NULL) {
        if (send(sockfd, data, sizeof(data), 0) == -1) {
            perror("[-]Error in sending file.");
            exit(1);
        }
        bzero(data, SIZE);
    }
}

The Writer function the use in the SERVER:

    void write_file(int sockfd, char *filename) {
    int n;
    FILE *fp;
    //char *filename = "new_data.txt";
    char buffer[SIZE];

    fp = fopen(filename, "w");
    while (1) {
        n = recv(sockfd, buffer, SIZE, 0);
        if (n <= 0) {
            break;
            return;
        }
        fprintf(fp, "%s", buffer);
        bzero(buffer, SIZE);
    }
}

CodePudding user response:

fgets() and fprintf() are used for reading and writing zero-terminated strings, not arbitrary binary data. fread() and fwrite() are your friends here. Something like:

Client:

#define CHUNK_SIZE 1024
char buffer[CHUNK_SIZE];

while ((num_bytes = fread(buffer, 1, CHUNK_SIZE, fp)) > 0)
{
    send(sockfd, buffer, num_bytes, 0);
}

Server:

// Same chunk size and buffer as above

while ((num_bytes = recv(sock, buffer, CHUNK_SIZE, 0)) > 0)
{
    fwrite(buffer, 1, num_bytes, fp);
}

Technically fwrite() and send() can write less bytes than you ask them to, and you really should loop until all bytes are written.

You should also technically open your files with modes "rb" and "wb" for binary files.

  • Related