C - strtok和strcmp

Señ*_*cis 2 c strtok strcmp

使用strtok和strcmp时遇到了一些麻烦.

//Handles the header sent by the browser
char* handleHeader(char *header){
        //Method given by browser (will only take GET, POST, and HEAD)
        char *method,*path, *httpVer;

        method = (char*)malloc(strlen(header)+1);
        strcpy(method,header);
        method = strtok(method," ");


        path = strtok(NULL," ");
        httpVer = strtok(NULL, " ");
        printf("\nMethod: %s\nPath: %s\nHTTP: %s\n",method,path,httpVer);


        printf("\nc1: %d\nc2: %d\n",strcmp(httpVer,"HTTP/1.0"),strcmp(httpVer,"HTTP/1.1"));

        if(!(!strcmp(httpVer,"HTTP/1.0") || (!strcmp(httpVer,"HTTP/1.1")))){
                printf("\ngive a 400 error\n");
                return "400 foo";
        }


        if(!strcmp(method,"GET")){
                //char *path = strtok(NULL," ");

                //If they request the root file, change the path to index.html
                if(!strcmp(path,"/")){
                        path = (char*)malloc(strlen(BASE_DIR) + strlen("/index.html")+1);
                        strcpy(path,"/index.html");
                }
                 return readPage(path,2);
        }
}
Run Code Online (Sandbox Code Playgroud)

如果我给它以下标题

GET / HTTP/1.0
Run Code Online (Sandbox Code Playgroud)

我得到这个输出:

Method: GET
Path: /
HTTP: HTTP/1.0


c1: 1
c2: -1

give a 400 error
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,strtok()正确地解析了字符串,但值c1和c2似乎没有意义(c1应该返回0,而是返回1).

这里发生了什么?

Ric*_*dle 6

我猜你没有给它这个:

GET / HTTP/1.0
Run Code Online (Sandbox Code Playgroud)

而是这个:

GET / HTTP/1.0\n
Run Code Online (Sandbox Code Playgroud)

或者可能这样:

GET / HTTP/1.0\r\n
Run Code Online (Sandbox Code Playgroud)

查看代码," HTTP"输出行和" c1" 行之间应该有一个空行,但是你有两行,暗示" HTTP"值本身包含换行符.

在值周围输出一些引号 - 我打赌你看到这个:

HTTP: "HTTP/1.0
"
Run Code Online (Sandbox Code Playgroud)