Reputation: 23
I want to extract some number from HTTP Get requests in C. for example if my HTTP request is like:
GET /getUIKVal?mdn=9860436150 HTTP/1.1
Host: api.end.point
I want number 9860436150 to be printed as output. I have already tried with sscanf() and atoi()
Upvotes: 1
Views: 351
Reputation: 12742
You can simply use sscanf
like below.
char* line = "GET /getUIKVal?mdn=9860436150 HTTP/1.1";
long long val ;
int ret = sscanf(line, "%*[^=]=%lld",&val);
printf("%lld\n", val) ;
Where %*[^=]=
will read and discard the string until it reaches =
and %ld
will read actual number in val
.
Upvotes: 1
Reputation: 35164
You could use strstr
to identify marker mdn=
and then either scan a number or a string. Note that for scanning the number you don't need to copy the respective contents; The code below shows how:
const char* content = "GET /getUIKVal?mdn=9860436150 HTTP/1.1";
const char* startOfNumber = strstr(content,"mdn=");
if (startOfNumber) {
startOfNumber += strlen("mdn=");
long number;
if (scanf("%ld",&number)==1) {
printf("the number is... %ld", number);
} else {
printf("no valid number after 'mdn='");
}
} else {
printf("marker 'mdn=' not found.");
}
I actually prefer the strstr
-solution over a solution where scanf
identifies both the marker and the number because it is hard to reason about syntax errors then.
Upvotes: 0