0

I have the following C String:

char teste[] = "POST /index.html HTTP/1.1\nHost: localhost:8000\nConnection: keep-alive\nContent-Length: 23\nCache-Control: max-age=0\nAccept: text/html,application/xhtml+x
ml,application/xml;q=0.9,*/*;q=0.8\n Origin: http://localhost:8000\nUser-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/
537.36\nContent-Type: application/x-www-form-urlencoded\nReferer: http://localhost:8000/index.html\nAccept-Encoding: gzip,deflate,sdch\nAccept-Language: pt-BR,pt;q=0.8,en-US;q=
0.6,en;q=0.4\n\nnome=thiago&idade=12313";

And i need to extract the POST parameters, which happens after the '\n\n':

\n\nnome=thiago&idade=12313";

The strtok seems to get stuck on the first '\n', so i think there's a better way of doing this. My code so far:

char *token = malloc(100);
char **value  = malloc(100 * sizeof(char *));
char **key  = malloc(100 * sizeof(char *));
int i;

for(i = 0; i < 100; i++)
{
   value[i] = malloc(100);
   key[i] = malloc(100);
}

/* This doesn't work */ 
token = strtok(teste, "\n\n");

Any ideas on how to solve this? Thanks!

1 Answer 1

1

You can use strstr() to locate the start of the parameters:

char *params = strstr(teste, "\n\n");
if (params != NULL) {
    params += 2; // now points to first key
    // ...
}

and then use strtok() to separate the key-value pairs in params.

Remark: strtok_r() is a reentrant version of strtok(), and (at least on OS X), strtok() is obsoleted by strsep().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.