如何将recv()收到的二进制数据写入文件

时间:2017-11-08 16:51:06

标签: c sockets http get recv

我想使用此命令将使用GET请求收到的所有内容保存到文件中:

./client http://example.com/1.jpg > image.jpg

我的recv_buf是2000个字节。

// Generate HTTP request
sprintf(send_buf, "%s %s %s%s %s%s", "GET", path, "HTTP/1.1\r\n", 
                                "HOST:", hostname, "\r\n\r\n");

send_len = strlen(send_buf); //length of request to send
bytes_send = send(sockfd, send_buf, send_len, 0);

if (bytes_send <= 0)
{
    perror("nothing sended\n");
    exit(1);
}

printf("Bytes send: %d\nSended message: %s\n", bytes_send, send_buf);

// receive data

do {
    bytes_recv = recv(sockfd, recv_buf, sizeof(recv_buf), 0);

    if (bytes_recv <= 0) 
    {
        perror("connection closed or error");
        close(sockfd);
        freeaddrinfo(results);
        exit(0);
    }

    printf("Bytes received: %d\n", bytes_recv);

    //write(1, recv_buf, bytes_recv);

} while (bytes_recv > 0);

我到目前为止我可以接收数据直到最后,但我不知道如何将所有“包”以正确的顺序组合到一个缓冲区,然后将其作为二进制数据(图像)保存到文件中。 / p>

输出是:

./client https://example.com/1.jpg
Bytes received: 2000
Bytes received: 1792
Bytes received: 2000
Bytes received: 1792
Bytes received: 639
connection closed or error: Success

1 个答案:

答案 0 :(得分:0)

您可以按如下方式使用reallocmemcpy

unsigned char* buf = 0;
int bufsize = 0;
do {
    bytes_recv = recv(sockfd, recv_buf, sizeof(recv_buf), 0);
    if (bytes_recv <= 0) 
    {
        perror("connection closed or error");
        close(sockfd);
        freeaddrinfo(results);
        exit(0);
    }

    buf = realloc(buf, bufsize + bytes_recv);
    memcpy(buf + bufsize, recv_buf, bytes_recv);
    bufsize += bytes_recv;

} while (bytes_recv > 0);

buf将不包含已读取的bufsize个字节。或者写入文件并使用malloc并再次读取该文件。