【发布时间】:2013-02-15 11:56:22
【问题描述】:
我真正需要提取的信息是:
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;
}
【问题讨论】:
-
我想说你正在寻找一个正则表达式,正则表达式。查找一些教程,这应该不是一个大问题:)
-
@dutt 如果他尝试使用正则表达式,那么他将遇到 2 个问题。
-
解析来自 Internet 的数据的合理解决方案包括检查缓冲区溢出和各种其他验证。
-
@AlexeyFrunze:任何问题的理智解决方案包括检查缓冲区溢出和各种其他验证。 :)
-
在重新发明轮子之前,您可能想阅读这里:gnu.org/software/libmicrohttpd