Question

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);
Was it helpful?

Solution 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);

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top