문제

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