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

标签 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);

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

输出是:

./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

最佳答案

您可以使用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 并再次读取该文件。

关于c - 如何将recv()接收到的二进制数据写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47185326/

相关文章:

c - 更新 C 库,导致堆损坏

c - 带有 bug 的链表的哈希表

c - 是否允许编译器向标准头文件添加函数?

c - 通过原始套接字传输以太网帧

http - 如何做 HTTP 等同于多播

supervisord 可以用于程序的内存和 CPU 使用情况分析吗

c++ - 在同一个套接字上多次写入 C++

java - 在互联网上使用程序时,ObjectInputStream$BlockDataInputStream.peekByte

javascript - 查询参数作为 javascript 函数添加到 HTTP

python - 如何将http header 添加到使用scapy嗅探的数据包中