I am trying to parse a HTTP request header. I need to pickup the first line:

GET / HTTP/1.1

However, the output for the code below is:

Method: (null)
Filename: (null)
Version: (null)
Client hostname: (null)

Why?

Code:

    char *token;
    const char delimiter[2] = " ";
    token = strtok(NULL, delimiter);
有帮助吗?

解决方案 2

The delimiter has to be " \r\n", otherwise some parts will be concatenated

    // Parse the request                                                                                  
    char *token;
    const char delimiter[6] = " \r\n";

    token = strtok(buffer, delimiter);
    method = token;
    printf("Method: %s\n", method);

    token = strtok(NULL, delimiter);
    filename = token;
    printf("Filename: %s\n", filename);

    token = strtok(NULL, delimiter);
    version = token;
    printf("Version: %s\n", version);

    while (token != NULL) {
      if (strstr(token, "Host:") != NULL) {
        token = strtok(NULL, delimiter);
        client_hostname = token;
        break;
      }
      token = strtok(NULL, delimiter);
    }

    printf("Client hostname: %s\n", client_hostname);

其他提示

The first time you call strtok you need to provide the string you want to split as the first argument. Subsequent calls to strtok need to use NULL as the first argument to get subsequent delimited strings.

Good luck.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top