簡體   English   中英

C - strtok和strcmp

[英]C - strtok and 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);
        }
}

如果我給它以下標題

GET / HTTP/1.0

我得到這個輸出:

Method: GET
Path: /
HTTP: HTTP/1.0


c1: 1
c2: -1

give a 400 error

正如您所看到的,strtok()正確地解析了字符串,但值c1和c2似乎沒有意義(c1應該返回0,而是返回1)。

這里發生了什么?

我猜你沒有給它這個:

GET / HTTP/1.0

而是這個:

GET / HTTP/1.0\n

或者可能這樣:

GET / HTTP/1.0\r\n

查看代碼,“ HTTP ”輸出行和“ c1 ”行之間應該有一個空行,但是您有兩行,這意味着“ HTTP ”值本身包含換行符。

在值周圍輸出一些引號 - 我打賭你看到這個:

HTTP: "HTTP/1.0
"

正如您從輸出中的空白行中看到的那樣(並且已經有幾個人已經說過), HTTP/1.0末尾有控制字符。 可以解決這個問題。

但是為什么要在C中編寫新的HTTP請求解析器? 這是2009年! 已經有很多它們已經存在,其中一些甚至是正確的,許多是自由許可的。 即使你確實需要編寫自己出於某種原因,你應該使用一個安全的語言(Python和Java的,Lua中,C#,Perl和東西 ),這樣,如果你犯了一個微不足道的錯誤計數的字符,你不結束在你的程序中有一個很大的安全漏洞。 (即使你不知何故必須使用C, strtok也是一個特別令人震驚的C函數。)

從您的輸出看起來,在HTTP / 1.0字符串的末尾可能有一個'/ n'? 里奇對我來說太快了;)

在對其進行標記之前,請嘗試修剪/刪除輸入字符串上的任何空白區域。

嘗試使用

strncmp(httpVer, "HTTP/1.0", 8)

這樣你就可以忽略尾隨空格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM