strsep怎么在这里工作?为什么呢?

时间:2016-08-10 04:09:53

标签: c string pointers server strsep

我正在尝试学习用C编写服务器,并且遇到了让我感到困惑的事情。我一直试图理解一些代码(不是我的)。我理解其中的大部分内容......除了这个parse函数中的一个关键元素。

具体来说,strsep()如何在下面的代码中工作?

我认为strsep()找到一个点(令牌?),在其中停止在一个字符串中,然后将结束切断,将余数存储在一个新变量中。例如在请求行中找到methodmethod = strsep(copyofLine, " ");

这对我来说很有意义。

但是,我不明白它是如何工作的:

//put request-target in abs_path abs_path = strsep(copyofLine, "]" + 1);

为什么HTTP请求行中会有]

也在这里:

HTTP_version = strsep(copyofLine, "\\");

为什么会出现倒退?请解释一下。

以下是完整功能。谢谢。

/**
 * Parses a request-line, storing its absolute-path at abs_path 
 * and its query string at query, both of which are assumed
 * to be at least of length LimitRequestLine + 1.
 */
bool parse(const char* line, char* abs_path, char* query)
{
    //allocate memory for copy of line
    char** copyofLine = malloc(sizeof(char**));
    //copy line into new variable
    strcpy(*copyofLine, line);
    //allocate memory for method and copy actual method into it
    char* method = malloc(sizeof(char*));
    method = strsep(copyofLine, " ");
    //if method is not get, respond to browser with error 405 and return false
    if (strcasecmp(method, "GET") != 0) {
        error(405);
        return false;
    }
    //put request-target in abs_path
    abs_path = strsep(copyofLine, "]" + 1);
    //if request-target does not begin with /, respond with 501 and return false
    if (abs_path[0] != '/') {
        error(501);
        return false;
    }
    char* HTTP_version = malloc(sizeof(char*));
    HTTP_version = strsep(copyofLine, "\\");
    if(strcasecmp(HTTP_version, "HTTP/1.1") != 0) {
        error(505);
        return false;
    }
    //if request-target contains a "", respond with error 400 and return false
    char* c = abs_path;
    if (strchr("\"", *c)) {
        error(400);
        return false;
    }
    //allocate memory for copy of abs_patg
    char** copyofAbs_path = malloc(sizeof(char**));
    //copy line into new variable
    strcpy(*copyofAbs_path, abs_path);
    for (int i = 0, n = strlen(*copyofAbs_path); i < n; i++) {
        for (int j = 0, m = strlen(*copyofAbs_path) - i; j < m; j++) {
            if (*copyofAbs_path[i] == '/' && *copyofAbs_path[i+1] == '?') query[j] = *copyofAbs_path[i+2];
            if (*copyofAbs_path[i] == '/' && *copyofAbs_path[i+1] != '?') query[j] = *copyofAbs_path[i+1];
            // if (strlen(query)) < 1) query = "";
            if (query[j] == '\0') break;
        }
    }

    free(HTTP_version);
    free(c);
    free(method);
    free(copyofLine);
    free(copyofAbs_path);
    return false;
}

0 个答案:

没有答案