I'm working on a program in C for a class that requires me to take a request-line and break it down into its subsequent pieces. It's for learning purposes, so I can expect a fairly standard request-line.
Thinking about the problem, I was going to march through each char in the request-line with some sort of for()
loop that creates a new string every time it encounters a SP
, but I was wondering if there was a way to use strchr()
to point to each "piece" of the request-line?
Since a request-line looks like method SP request-target SP HTTP-version CRLF
where SP
is a single space, is there some way I could create a function that uses strchr(request-line, ' ')
to create a string
(or char*
or char[ ]
) that then ENDS at the next SP
?
edit:
So I could do something like
char method = strchr(request-line, ' ');
But then, wouldn't "method" be every char after the SP
? How can I "trim" what gets put into my variable? Or am I totally misunderstanding how this function works?
You can technically use strtok but it will modify the request line in place, which may be acceptable, but not in every situation. Here is a generalized solution:
char *method, *target, *version;
const char *p = request_line, *p1;
while (*p != ' ')
{
p++;
}
method = strndup(request_line, p - request_line);
p1 = ++p;
while (*p != ' ')
{
p++;
}
target = strndup(p1, p - p1);
p1 = ++p;
while (*p != '\r')
{
p++;
}
version = strndup(p1, p - p1);
As you expect only well-formatted input, I omitted all error checks.