【发布时间】:2014-06-28 01:47:04
【问题描述】:
我是 C 新手,我已经为这个任务工作了大约 7 个小时 - 请不要说我没有尝试。
我想用C解析一个自己写的webserver的路径。假设我调用
http://localhost:8080/hello/this/is/a/test.html
然后浏览器获取
GET /hello/this/is/a/test.html HTTP/1.1
我想解析/hello/this/is/a/test.html,所以“GET”(注意GET之后的空格)和/../../..html之后的第一个空格之间的完整字符串。
到目前为止我尝试了什么:
int main() {
...
char * getPathOfGetRequest(char *);
char *pathname = getPathOfGetRequest(buf);
printf("%s\n\n%s", buf, pathname);
...
}
char * getPathOfGetRequest(char *buf) {
char *startingGet = "GET ";
char buf_cpy[BUFLEN];
memcpy(buf_cpy, buf, sizeof(buf));
char *urlpath = malloc(1000);
char *path = malloc(1000);
urlpath = strstr(buf_cpy, startingGet);
char delimiter[] = " ";
path = strtok(urlpath, delimiter);
path = strtok(NULL, delimiter);
return path;
}
路径名始终只有 4 个正确的字符,并且可能填充或不填充其他不相关的字符,例如 /hell32984cn)/$"§$。我猜它与strlen(startingGet)有关,但我看不出它之间的关系。我的错在哪里?
【问题讨论】:
-
如果问题指出,具体来说,
/hello/this/is/a/test.html的解析结果是什么,也许会有所帮助?只是从字符串的开头删除'GET'?在分配的存储中返回? -
你说得对,谢谢。我编辑了这个问题。我需要解析 GET 之后的空白和后面的字符串结尾之间的所有内容,直到我点击下一个空白。
-
除非你绝对需要在 XXkb 下获取程序,否则只需使用 sscanf - strtok/strsep 太可怕了。