简体   繁体   English

如何从在 C++ 中使用 recv 接收的数据中去除标头?

[英]How to Strip the header from data received using recv in c++?

I have made this code below to download large file and save it to file.我在下面制作了这段代码来下载大文件并将其保存到文件中。 (I removed not important parts) (我删除了不重要的部分)

int nDataLength;
int i = 0;
static char buffer[4096];
while ((nDataLength = recv(Socket, buffer, sizeof(buffer), NULL)) > 0)
{
    //MessageBoxA(0, std::to_string(nDataLength).c_str(), "TEST", 0);
    fwrite(buffer, nDataLength, 1, pFile);
}

Now It saves file, but it also saves HTTP header.现在它保存文件,但它也保存 HTTP 标头。 Now I don't really know how to strip the header from received data.现在我真的不知道如何从接收到的数据中去除标题。
If it was small enough I could read Content-Length from buffer and then open the file again and remove header, but thats not the option cause buffer will be overwritten with new data.如果它足够小,我可以从缓冲区读取内容长度,然后再次打开文件并删除标题,但这不是选项,因为缓冲区将被新数据覆盖。

Also I cannot use other libraries like libcurl etc.我也不能使用其他库,如 libcurl 等。

EDIT:编辑:

char* content = strstr(buffer, "\r\n\r\n");
    if (content != NULL) {
        content += 4;
        fwrite(content, nDataLength, 1, pFile);
    }
    else
    {
        fwrite(buffer, nDataLength, 1, pFile);
    }

OK, I came up with function that strips header before saving.好的,我想出了在保存之前去除标题的功能。

 int nDataLength;
int i = 0;
static char buffer[4096];
while ((nDataLength = recv(Socket, buffer, sizeof(buffer), NULL)) > 0)
{
    char* content = strstr(buffer, "\r\n\r\n");
    if (content != NULL) {
        std::string s2(buffer); 
        size_t p = s2.find("\r\n\r\n");
        fwrite(buffer+p+4, nDataLength-p-4, 1, pFile);
    }
    else
    {
        fwrite(buffer, nDataLength, 1, pFile);
    }
    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C++ recv 网卡接收数据时收不到任何东西 - C++ recv not receiving anything when NIC received data 如何使用c++通过recv()函数接收大数据? - How to receive big data with recv() function using c++? 使用gSoap时如何解释C ++中的接收数据? - How to interpret the received data in C++ when using gSoap? 如何使用winsock(c ++)发送\ recv非char数据? - How to send\recv non char data with winsock (c++)? 如何使用C ++中的recv或read函数从tcp套接字读取大请求? - How to read large request from tcp socket using recv or read function in C++? C ++ TCP套接字通信-连接按预期工作,几秒钟后失败,未接收到新数据并且read()和recv()块 - C++ TCP Socket communication - Connection is working as expected, fails after a couple of seconds, no new data is received and read() and recv() block 在C ++中recv()未收到HTTP请求的数据 - no data recieved by recv() for https request in c++ 使用 C++ 中的部分 recv() 检查 HTTP 响应 header - Check HTTP response header with partial recv() in C++ c ++ Winsock发送,recv-他们的工作方式 - c++ Winsock send,recv -how they work 通过套接字传输数据[TCP] 如何在 c/c++ 中打包多个 integer 并使用 send() recv() 传输数据? - Data transfer over sockets[TCP] how to pack multiple integer in c/c++ and transfer the data with send() recv()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM