2

I am having a problem where I am trying to split an HTTP request by a carriage return for a web proxy. The request does not seem to split.

Here is an example request: GET /pub/WWW/TheProject.html HTTP/1.1\r\nHost: www.w3.org\r\n

My attempt is:

char* split_request;
split_request = strtok(request, "\r\n");

But it never gets split? I am not sure what I am missing. It seems to split when I am using wget or the browser to test the web proxy, but doesn't with telnet.

1
  • You seem to assume this is C's variant of split in other languages; it is not. strtok scans for any character in its argument string.
    – Jongware
    Commented Nov 24, 2014 at 9:49

2 Answers 2

11

Are you doing this way?

#include <stdio.h>
#include <string.h>

int main (void)
{
    char str[] = "GET /pub/WWW/TheProject.html HTTP/1.1\r\nHost: www.w3.org\r\n";
    char* pch = NULL;

    pch = strtok(str, "\r\n");

    while (pch != NULL)
    {
        printf("%s\n", pch);
        pch = strtok(NULL, "\r\n");
    }
    return 0;
}

Output:

GET /pub/WWW/TheProject.html HTTP/1.1   
Host: www.w3.org
2
  • This is clearly not C. Tempted to downvote, except that your string handling is correct.
    – Jongware
    Commented Nov 24, 2014 at 9:51
  • 2
    I overlooked the header files iostream and cstring. Edited it now.
    – Jagannath
    Commented Nov 24, 2014 at 9:53
3

Check the below link:

How does strtok() split the string into tokens in C?

int main()
{
    char request[20]="some\r\nstring";
    char* split_request;
    split_request = strtok(request,"\r\n");
    while(split_request != NULL)
    {
       printf("%s\n",split_request);
       split_request = strtok(NULL,"\r\n");

    }

    return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.