如何确定" Content-Length的长度:"在HTTP数据包中

时间:2014-09-22 20:13:48

标签: c http http-headers

我正在为嵌入式目标上的http服务器编写代码。我想解析我收到的原始HTTP数据包的内容长度。我的问题是因为我不知道内容长度是多少字节。例如,

//内容长度为4个字符
内容长度:1000

// Content-Length是2个字符
内容长度:20

我的代码是:

(buf is a char array with the contents of the http data, pLength is a char *)
pLength = strstr(buf, lenTok);
//advance pointer past "Content-Length: " to point to data
if (pLength != NULL) 
    pLength = (pLength + 16);
int length = 0;
for (int i = 0; i < /*length of Content-Length:*/; i++)
{
    length = length * 10;
    length = length + (pLength[i] - '0');
}

我知道我的代码有效,因为现在我已经在循环迭代器条件中放置了一个硬编码值。我只需要能够在运行时确定它。

编辑:在找到\ r之前继续阅读字符是否安全?

2 个答案:

答案 0 :(得分:2)

标题中的每一行以每section 3 of RFC7230个CR / LF对结束。在同一文档的第3.2.4节中,它表示“字段值可能在可选空格之前和/或之后”。因此,要成功解析内容长度,您的代码必须跳过任何前导空格,然后处理数字,直到找到空白字符。换句话说

int i;
int count = 0;
int length = 0;

for ( i = 0; isspace( pLength[i] ); i++ )
{
    // skip leading whitespace
}

for ( count = 1; !isspace( pLength[i] ); i++, count++ )
{
    if ( count > 9 || !isdigit( pLength[i] ) )
    {
        // some sort of error handling is needed here
    }
    length = length * 10;
    length = length + (pLength[i] - '0');
}

请注意,检查count > 9会将内容长度限制为999,999,999。根据您的应用需要进行调整。例如,如果int为64位,则可以支持更大的数字。另一方面,也许您只想支持较小的长度,在这种情况下,您可以将位数限制为较小的值。

答案 1 :(得分:1)

解决这个问题的一种方法是简单地从固定长度的字符串&#34; Content-Length:&#34;之后开始计数。直到找到空格或空字节(在某些罕见的情况下)。

#define INITIAL_LENGTH (16) /* Length of the string "Content-Length: " */

if (pLength == NULL)
    return /* or whatever */
else
    pLength += INITIAL_LENGTH

int length;
for(length = 0; *pLength != 0 && *pLength != '\n'; ++pLength)
    length++;

pLength -= length; /* Now it points right after Content-Length:  */
/* Now you have the length */