recv()函数中HTTP头的处理不一致

时间:2016-04-02 02:38:35

标签: c apache http

我想使用下面的代码从邮件中获取HTTP接收标头,但有时它运行良好,有时它不会。

以下是我要发送的代码:

send(s, message, strlen(message), 0)

这就是我收到数据的方式:

int memory = 1;
int d = 0;
header = malloc(memory * sizeof(char));
if (header == NULL) {
    printf("Error, memory\n");
    return 1;
}
while (recv(s, header + d, 1,0)>0) {
    if(strstr(header, "\r\n\r\n") != NULL)
        break;

    d++;
    if (d >= memory) {
        memory *= 2;
        header = realloc(header, memory);
        if (header == NULL) {
            printf("Error, memory\n");
            return 1;
        }
    }
}

我认为malloc存在问题,但我无法找到。

这是一个成功的接收标头,根据w3.org

Header:
HTTP/1.1 200 OK
Date: Sat, 02 Apr 2016 02:35:07 GMT
Last-Modified: Tue, 24 Feb 2015 20:49:22 GMT
ETag: "7ab4-50fdba7431880;50c0cc9312bdc"
Accept-Ranges: bytes
Content-Length: 31412
Cache-Control: max-age=2592000
Expires: Mon, 02 May 2016 02:35:07 GMT
P3P: policyref="http://www.w3.org/2014/08/p3p.xml"
Vary: upgrade-insecure-requests
Access-Control-Allow-Origin: *
Connection: close
Content-Type: image/png; qs=0.7

根据apk-dl

,这是失败信息中的一个
Header:
HTTP/1.1 200 OK
gEp7qN_agFirScA9OVXmWLV8ofyAZngl0Q_Sc-K50=h500.png HTTP/1.1
Host: apk-dl.com
Connection: close 

如何正确且一致地解析标题?

2 个答案:

答案 0 :(得分:2)

由于无法正确完全处理recv()返回的结果而无法正常工作,滥用strxxx()调用不保证以null结尾的字符数组,无法理解底层TCP的八位字节流性质只能传输一个字节或更少字节的消息以及误用malloc的协议 - 只为头缓冲区分配一个字节。

答案 1 :(得分:0)

Ryans-MacBook-Air:~ Ryan-Macintosh$ /Users/Ryan-Macintosh/Desktop/bash.sh ; exit; 函数仅适用于C风格的字符串。您不能将它用于任意数据。一种可能性是使用像this这样的 #! /bin/bash export PS1="" echo "HUGE BLOCK OF TEXT HERE THAT IS TOO LONG TO PASTE" $SHELL 类型函数。

我强烈建议您停止发送HTTP 1.1请求并发送HTTP 1.0请求。你必须做很多事情才能建立一个你可能不会处理的HTTP 1.1客户端(比如处理分块编码)。