gpt4 book ai didi

c - 在 C 中解析 HTTP 请求行

转载 作者:太空狗 更新时间:2023-10-29 15:19:16 26 4
gpt4 key购买 nike

这是永远不会结束的问题。任务是在 C 中解析 Web 服务器中的请求行——长度不确定。我从 Web 上提取了以下内容作为示例。

GET /path/script.cgi?field1=value1&field2=value2 HTTP/1.1

我必须提取绝对路径:/path/script.cgi 和查询:?field1=value1&field2=value2。我被告知以下函数是关键:strchrstrcpystrncmpstrncpy 和/或strstr.

这是到目前为止发生的事情:我了解到使用像 strchrstrstr 这样的函数绝对允许我在某些点截断请求行,但会永远不要让我摆脱我不想要的请求行的部分,而且我如何对它们进行分层并不重要。

例如,这里有一些代码让我接近隔离查询,但我无法消除 http 版本。

bool parse(const char* line)
{
// request line w/o method
const char ch = '/';
char* lineptr = strchr(line, ch);

// request line w/ query and HTTP version
char ch_1 = '?';
char* lineptr_1 = strchr(lineptr, ch_1);

// request line w/o query
char ch_2 = ' ';
char* lineptr_2 = strchr(lineptr_1, ch_2);

printf("%s\n", lineptr_2);

if (lineptr_2 != NULL)
return true;
else
return false;
}

不用说,我有一个类似的问题试图隔离绝对路径(我可以放弃方法,但不能放弃 ? 或之后的任何东西),而且我看不到任何场合我可以使用需要我的功能先验我想从一个位置(通常是一个数组)复制多少个字符到另一个位置,因为当它实时运行时,我不知道请求行会是什么样子喜欢提前。如果有人看到我遗漏的东西并能指出正确的方向,我将不胜感激!

最佳答案

更优雅的解决方案。

#include <stdio.h>
#include <string.h>

int parse(const char* line)
{
/* Find out where everything is */
const char *start_of_path = strchr(line, ' ') + 1;
const char *start_of_query = strchr(start_of_path, '?');
const char *end_of_query = strchr(start_of_query, ' ');

/* Get the right amount of memory */
char path[start_of_query - start_of_path];
char query[end_of_query - start_of_query];

/* Copy the strings into our memory */
strncpy(path, start_of_path, start_of_query - start_of_path);
strncpy(query, start_of_query, end_of_query - start_of_query);

/* Null terminators (because strncpy does not provide them) */
path[sizeof(path)] = 0;
query[sizeof(query)] = 0;

/*Print */
printf("%s\n", query, sizeof(query));
printf("%s\n", path, sizeof(path));
}

int main(void)
{
parse("GET /path/script.cgi?field1=value1&field2=value2 HTTP/1.1");
return 0;
}

关于c - 在 C 中解析 HTTP 请求行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41286260/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com