Send binary file over TCP/IP connection

前端 未结 2 1982
南方客
南方客 2020-12-06 04:17

I will rephrase the whole question here so that it is answerable.

I am able to copy binary file perfectly in the same machine not using sockets but just making a sim

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 04:18

    We could avoid the header that contains the image size, but we just read to the end of the sent data. About the buffer size, we could use a fixed number such as 10 * 1024, when we received some data from the server, we just save it into a file according to the actual received data length.

    // please open a file ...
    FILE * fp;
    // ...
    const int LENGTH = 10 * 1024;
    
    int len = 0;
    char * buffer = (char *)malloc(LENGTH);
    while ((len = recv(socket, buffer, LENGTH, 0)) > 0) {
        fwrite(buffer, 1, len, fp);
    }
    free(buffer);
    // close the file
    

    @T.C: I guess we cannot allocate a buffer according to the size sent from the server in case the image is too large to save inside the client's memory. Not mention the server is fake, and intended to make any attack.

提交回复
热议问题