c - 如何用 C 最有效地解析此 HTTP 请求?

标签 c string http parsing

我真正需要提取的信息是:

a) 是否是GET请求

b) 文件地址(例如index.html)

c) 主机信息(例如 localhost:8081)

我现在有代码可以执行此操作(请参阅我的帖子底部),但它似乎效率低下,非常静态,并且不会提取主机信息。

所以我想要一个理智的解决方案来解析 C 中的 HTTP 请求。干杯!

HTTP 请求

GET /index.html HTTP/1.1
Host: localhost:8081
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.70 Safari/537.17
DNT: 1
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,en-GB;q=0.6
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

当前代码

int parsehttp(char *inputstring, int *type, char *getaddress) {
    if((strncmp(inputstring, "GET", 3)) == 0) {
        *type = 1;
    } else {
        *type = 0;
    }
    char firstline[BUFLEN] = "";
    int charoffset = getlineend(inputstring); //this function returns the int offset of '\r\n'
    strncpy(firstline, inputstring, charoffset-2);
    firstline[charoffset-1] = '\0';
    sscanf(firstline,"%*s %s %*s",getaddress);
    inputstring = (inputstring + charoffset);
    return 1;
}

最佳答案

strstr 函数可能对您有帮助。它尝试在您提供的字符串中找到给定的字符串。由于 HTTP 请求由以 0xD、0xA 结尾的行组成,因此您可以拆分这些行。 通常,一行文本的信息是使用空格分隔的。 因此,要查找“GET”或“POST”,请使用

char* getpost = strstr("GET /index.html HTTP/1.1", "GET");

如果 getpost 为 != NULL,您将获得字符串并可以在 GET 或 POST 之后剪切它。

其次,您将查找“主机:”并跳过该部分,直到到达 0xD、0xA,这样您就获得了主机地址。

参见strstr有关 strstr 的联机帮助页。

关于c - 如何用 C 最有效地解析此 HTTP 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14894214/

相关文章:

c# - 需要帮助将此代码段从 c 转换为 c#

python - 连接字符串 : "Multiplication" of two list of strings

java - Http 到 https 重定向

javascript - 使用异步 Javascript 调用接收数据

带分号的 C 参数出现被截断

c - “?”不适用于 C Posix 正则表达式

c - 如何使数据类型小于 32 位

C# 静态类与预定义字符串的结构

java - 用Java分割和大写字符串中的单词

复制到本地主机后,Wordpress 总是重定向到 https